Why isn't subclass constructor overriding?
I have the code:
class Oak extends Tree {
public Oak() {
System.out.println("Oak()");
}
}
class Tree {
开发者_JAVA技巧public Tree() {
System.out.println("Tree()");
}
}
class mainClass {
public static void main(String[] args) {
Oak a = new Oak();
}
}
Why does it print
Tree()
Oak()
instead of just
Oak()
?
An Oak
is a kind of Tree
, so the Tree
part of the object must be constructed first. Therefore the default Tree
constructor is called. Subsequently, the Oak
constructor can run.
This is exactly equivalent to explicitly calling the Tree
constructor in the Oak
constructor as the first statement:
public Oak() {
super();
...
}
[Note that constructors don't "override".]
Constructors are never inherited, and never overriden. That means, the parent's constructor will always execute when creating an instance of the child class. Therefore, you get both messages
Derived class object construction takes places in the order of base class subobject construction and derived class subobject construction.
constructors will be called from Root class to child in downwards order. there is not overriding concept in constructors.
Constructors cannot be overridden; overriding only applies to non-static, non-private methods.
There's one important thing you have to understand about inheritance. It implies an is a relationship between the subclass and the superclass. So, an instance of the subclass is an instance of its superclass, with the subclass-specific things added to it. For example, an Oak is a Tree.
That means that part of the Oak object is the Tree object. When an Oak object is created, first the superclass part of the object is created and initialized. This involves calling a constructor of the superclass (the constructor of Tree, in your example). After that, the subclass parts are added to the object, and for that the constructor of Oak is called.
When you create an object, you have to call a constructor of the superclass. You can either specify explicitly which constructor of the superclass you call or not, in which case no-arguments constructor is called. That's why you get call to Tree(). If you didn't have a no-arguments constructor, then there would be an error:
class Oak extends Tree {
public Oak() {
super("Oak Tree"); //Without this line the code won't compile
System.out.println("Oak()");
}
}
class Tree {
public Tree(String name) {
System.out.println("Tree(" + name + ")");
}
}
class mainClass {
public static void main(String[] args) {
Oak a = new Oak();
}
}
精彩评论