• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Ranch Hand
Posts: 108
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.
 
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.
 
Bartender
Posts: 4568
9
  • X 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
 
I was born with webbed fish toes. This tiny ad is my only friend:
The WEB SERVICES and JAX-RS Course
https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!