Question
Consider two classes A and B:
A.java
public class A{ public A(){ // lots of constructor activity. } }
B.java
public class B extends A{ public B(){} }
There are no other constructors for either A or B.
Does the constructor for A get called when a B is constructed?
Or do I need to add the following line to get A constructed?
B.java
public B{ super(); }
Answer
There are two bizarre Java rules:
- If a java class has no explicit constructor it is assumed to have an "implicit" empty public no-arg constructor:
MyClass.java
public MyClass(){}
- If a constructor does not explicitly call either the super constructor or another of its own constructors (using
this(args)
) it is assumed to have an "implicit" call tosuper()
as the first line of the constructor. Note also thatthis()
orsuper()
can only be called as the first line of a constructor.
Relying on either of these is generally considered to be in bad taste, so you should always have at least one constructor, and you should always explicitly call the super class's constructor.