• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

A subclass object would invoke superclass constructor?

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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??
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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();").
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
jaspreet atwal
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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!!
reply
    Bookmark Topic Watch Topic
  • New Topic