aspose file tools*
The moose likes Beginning Java and the fly likes A subclass object would invoke superclass constructor? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A subclass object would invoke superclass constructor?" Watch "A subclass object would invoke superclass constructor?" New topic
Author

A subclass object would invoke superclass constructor?

jaspreet atwal
Ranch Hand

Joined: Sep 05, 2007
Posts: 52
Hi Guys,
I have a superclass with a constructor superclass().
I have a subclass that extends superclass and has its own constructor.
I create an object of subclass
subclass obj = new subclass();

Now my question is would this also invoke constructor for superclass??


Still Learing..
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Yes. The first statement of every class's constructor must either invoke another constructor (e.g. "this(42);") or a superclass constructor (e.g. "super(42);"). If neither is explicitly specified in your constructor code, the compiler will automatically add a call to the no-arguments superclass constructor (i.e. "super();").


SCJP 5.0
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

This is easily demonstrated with the following test code...

Consider: If SubClass extends SuperClass, then any instance of SubClass IS-A SuperClass. So the first step in creating an instance of SubClass is to create an instance of SuperClass.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
jaspreet atwal
Ranch Hand

Joined: Sep 05, 2007
Posts: 52
Originally posted by marc weber:
This is easily demonstrated with the following test code...

Consider: If SubClass extends SuperClass, then any instance of SubClass IS-A SuperClass. So the first step in creating an instance of SubClass is to create an instance of SuperClass.





Marc, This clears my confusion. Thanks!!
 
 
subject: A subclass object would invoke superclass constructor?