This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
I'm learning Java basics and while playing around with inheritance, I found something that I cannot understand.
(Below) I created two classes (class1 and class2) and class2 extends class1. Now, when I instantiate an object of sub class2 in my main method and run the code both constructors are run, because I'm seeing the println statements from both class' constructors in my output.
Is it just a simple fact that when you instantiate an object that extends another object, it runs both child and parent constructors? Maybe I'm missing something.
Go and look at your subclass. You can have methods in it which aren't in the superclass, and fields which aren't in the superclass. But you also have fields from the superclass and methods from the superclass. So whenever you instantiate the subclass, you have to set up the superclass fields too. To do this, you call the superclass constructor from the subclass constructor. That is what super() means.
Joined: Dec 22, 2007
Thanks! Ok, that makes sense... so because I'm instantiating the sub-class which is part of the super, the super needs to be 'set up' too.
Ok, the only question remaining is because you said that, "To do this (set up superclass), you call the superclass constructor from the subclass constructor.(i.e. super())"
But, I actually never explicitly called super(), so am I right to assume that super() is run regardless, even if I don't explicitly call the superclass constructor from the subclass?
Joined: Oct 13, 2005
Only too pleased to be of help . . .
It is probably an inaccurate thing to say, but there is a part of the subclass which comes from the superclass, not a part of the superclass which comes from the subclass.
You presumably know that you have to write super(something); as the first line of the constructor in the subclass. There are exceptions:
if you have an overloaded constructor, when you can start with this(something); in some of the constructors.
If you have a no-arguments constructor in the superclass, then the compiler or JVM will "assume" you have an implicit "super();" in your constructor, even if you haven't written it.
Yes, there is an implicit super(); call if you don't write it yourself. If there is a super(); call and the superclass constructor requires any parameters, you have to supply arguments to match those parameters, otherwise you get a compiler error saying it can't find the constructor. [ December 22, 2007: Message edited by: Campbell Ritchie ]