Constructors of Sub and Super Classes in Java?
Join the DZone community and get the full member experience.
Join For Freethis post summarizes some commonly asked questions from stackoverflow.com.
1. why creating an object of the sub class invokes also the constructor of the super class?
class super { string s; public super(){ system.out.println("super"); } } public class sub extends super { public sub(){ system.out.println("sub"); } public static void main(string[] args){ sub s = new sub(); } }
it prints:
super sub
when inheriting from another class, super() has to be called first in the constructor. if not, the compiler will insert that call. this is why super constructor is also invoked in the code above.
this doesn’t create two objects, only one sub object. the reason to have super constructor called is that if super class could have private fields which need to be initialized by its constructor.
after compiler inserts the super constructor, the sub class constructor looks like the following:
public sub(){ super(); system.out.println("sub"); }
2. a common error message: implicit super constructor is undefined for default constructor
this is a compilation error message seen by a lot of java developers. “implicit super constructor is undefined for default constructor. must define an explicit constructor”
this compilation error is caused because the super constructor is undefined. in java, if a class does not define a constructor, compiler will insert a default one for the class, which is argument-less. if a constructor is defined, e.g. super(string s), compiler will not insert the default argument-less one. this is the situation for the super class above.
since compiler tries to insert super() to the 2 constructors in the sub class, but the super’s default constructor is not defined, compiler reports the error message.
to fix this problem, simply add the following super() constructor to the super class, or remove the self-defined super constructor.
public super(){ system.out.println("super"); }
3. explicitly call super constructor in sub constructor
the following code is ok:
the sub constructor explicitly call the super constructor with parameter. the super constructor is defined, and good to invoke.
4. the rule
in brief, the rules is: sub class constructor has to invoke super class instructor, either explicitly by programmer or implicitly by compiler. for either way, the invoked super constructor has to be defined.
5. the interesting question
why java doesn’t provide default constructor, if class has a constructor with parameter(s)?
some answers: http://stackoverflow.com/q/16046200/127859
Published at DZone with permission of Ryan Wang. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments