An instance of the subclass is an instance of the superclass. Only one object is created, but as part of that creation, constructor calls are chained together all the way up to java.lang.Object
. So for example:
public class Superclass {
// Note: I wouldn't normally use public variables.
// It's just for the sake of the example.
public int superclassField = 10;
public Superclass() {
System.out.println("Superclass constructor");
}
}
public class Subclass extends Superclass {
public int subclassField = 20;
public Subclass() {
super(); // Implicit if you leave it out. Chains to superclass constructor
System.out.println("Subclass constructor");
}
}
...
Subclass x = new Subclass();
System.out.println(x instanceof Subclass);
System.out.println(x instanceof Superclass);
System.out.println(x.superclassField);
System.out.println(x.subclassField);
The output of this is:
Superclass constructor
Subclass constructor
true
true
10
20
... because:
- The first thing any constructor does is call either another constructor in the same class, or a superclass constructor. So we see "Superclass constructor" before "Subclass constructor" in the output.
- The object we've created is (obviously) an instance of
Subclass
- The object we've created is also an instance of
Superclass
- The single object we've created has both fields (
superclassField
and subclassField
). This would be true even if the fields were private (which they usually would be) - the code in Subclass
wouldn't be able to access a private field declared in Superclass
, but the field would still be there - and still accessible to the code within Superclass
.
The fact that we've got a single object with all the state (both superclass and subclass) and all the behaviour (any methods declared within Superclass
can still be used on an instance of Subclass
, although some may be overridden with more specializd behaviour) is crucial to understanding Java's approach to polymorphism.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…