File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes constructor up and down hierarchy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "constructor up and down hierarchy " Watch "constructor up and down hierarchy " New topic
Author

constructor up and down hierarchy

naveen yadav
Ranch Hand

Joined: Oct 23, 2011
Posts: 384



Look a code



It gives compile time error.
It seems to me that compiler insert no-arg default constructor for class Cert. and don't find no-arg constructor in Marmaduke.

when a object is instantiated for subclass , then instantiation of its super class must be done first. i.e you have to complete the UP hierarchy

my doubt is :

i am creating instance of Marmaduke class . So i must ensure the instantiation of Marmaduke and Object class which is UP hierarchy.which is fine since compiler will place super() in Marmaduke fo Object class.

but why do i have to worry about the Cert i.e. DOWN hierarchy ??



Regards
naveen




Tomasz Sochanski
Ranch Hand

Joined: Jan 13, 2009
Posts: 47

Extending class has to define constructor, which can call constructor of extended class with corresponding argument list. Compiler puts call to super(...) constructor in every first line of your extending class constructors.
You don't define any constructor in extending class, so compiler puts default no-arg, but it cannot insert call to super() with no args, so refuses to compile such a code.
It doesn't matter you don't instantiate extended class in your code.
naveen yadav
Ranch Hand

Joined: Oct 23, 2011
Posts: 384



it means compiler will check constructor for every class in parent and child class relationship , irrespective of class you are instantiating.

it starts constructor chaining right form child class to Object class. Is that it ?
Tomasz Sochanski
Ranch Hand

Joined: Jan 13, 2009
Posts: 47

naveen yadav wrote:

it means compiler will check constructor for every class in parent and child class relationship , irrespective of class you are instantiating.

it starts constructor chaining right form child class to Object class. Is that it ?

Yes, exatcly. Please notice, that you can instatiate object without using new operator - ie. you can do this dynamically with reflection API - how compiler would determine if you would or would not do this?
naveen yadav
Ranch Hand

Joined: Oct 23, 2011
Posts: 384

thanks Tomasz Sochanski .
 
GeeCON Prague 2014
 
subject: constructor up and down hierarchy