Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the use of SUPER call in the derived class constructor?

 
Pavan Kumar Dittakavi
Ranch Hand
Posts: 106
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

Let us say that we have a class A as follows.

Class A
{
private int a;
public int b;
}

And class B, which extends class A.

Class B extends A
{
int c;
}

Now, if I create an object for B, then will it be having the member variable 'b' as we have inherited?
The answer is YES.

But if that is the case, generally why do we use a call to SUPER in the B class' constructor?..Obviously super creates an instance of class A. But why?

Thanks,
Pavan.
 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
B class calls super in its constructor to create class A object. This is required because class B extends class A. Which essentially means that class B inherit some characteristics of class A. Now to make it possible, it is required that class B object should contain class A object also.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's misleading to say that class B object contains a class A object - it doesn't. It is a class A object. And it's also not true that super() creates an instance of class A.

I'd put it like this. Constructors don't create objects, they initialise them. A class B object IS-A class A object, and so the parts of it that it's inherited from class A need to be initialised as well. That's why the super-class constructor must always be called.

 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Matthew for replying to this post.
Yes you are correct. Agreed
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic