• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling super() method .

 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At java, We need to call super class constructor in base class constructor
at first line itself , other wise compiler will kick .

Could any one explain me why we need to put at first line itself ?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49803
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More of a beginner's question.

Look at this tutorial about the Object class, and this tutorial about super().

Imagine you have a class which is partially made up from parts unchanged from its superclass and partially from parts it has itself. To set up an object you have to set up the parts from the class and the parts from the superclass. Well, Java insists you set up the parts from the superclass first.

If you search above you find old discussion including this, this and this.
 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have seen that constructors can not be inherited and we should not
use any instance variable and instance methods before calling super class
constructor.

Am i right ?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49803
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. The compiler will insist the super() call come first.
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first line in any constructor is either a call to super(x) or to this(x). The first will call the matching constructor of the super class, with x being zero or more parameter values. The second will call the matching constructor in the same class.

If you don't put either of these in your code, the compiler will add a call to super() for you.
 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, can any one give stright reason why we should call them in first line ?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49803
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I presume because the designers of the language thought that creating the superclass part of the object should be done first. It also means the compiler can easily find out if you forget your "super()" call.
[ May 06, 2008: Message edited by: Campbell Ritchie ]
 
jaspreet atwal
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check you private messages.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic