Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

calling this()

 
Rajat Sarkar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public abstract class Animal
{
private int teeth_number;

public Animal(int x)
{
teeth_number=x;
}

public Animal()
{
this(10);
System.out.println("These do not execute"); // this line does not execute }

public int showTeeth()
{
return teeth_number;
}

public abstract void roam();
}

Why the underlined line does not execute while creating subclasses of Animal?

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would execute if the subclass invokes the no-argument constructor of the superclass; but if the subclass uses "super(32)" or otherwise calls the constructor with an int argument, the no-argument constructor will not be executed.
 
Melissa Raven
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This ran fine for me:



Cheers
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic