Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor Doubt

 
Deepak Bobal
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class top
{
public top() //line 3
{
System.out.println("top");
} //line 6
public top(String s)
{
System.out.println("BB");
}
}
public class bottom2 extends top
{
public bottom2(String s)
{
System.out.println("DD");
}
public static void main(String[] arg)
{
new bottom2("CC");
System.out.println("Invoked ");
}
}


In the above code sample
Output is >
top
DD
Invoked
************************************
Why "BB" is not getting printed???
***************************************
If i am right the program flow is
1:new button2("CC");
2:calls it's super class constructor > public top(String s)
3:then it class it's super class constructor......keeps on to Object class
4:then starts initialization
This way it happens.If my floe to understand this is wrong, please suggest me.
**********************************
My second question is if i comment from line 3 to line 6 ,it shows compilation error.According to me it shouldn't .As Class top and bottom2 have same argument constructor.


thanks
Deepak
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
2:calls it's super class constructor > public top(String s)


Why do you believe that a constructor will call the super constructor with the same signature? If this was true, then wouldn't the Object class need a constructor for every possible combination of constructors?

Henry
 
Ajay Singh
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your second point is wrong,super makes an implicit call to the no argument constructor of the parent class instead of the argument constructor.If you comment those lines super cant find a no argument constructor of the parent class and hence the error.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic