Please look at this code:
class Sup {
int a = 8;
public void printA() {
System.out.println(a);
}
Sup() {
printA();
}
}
public class Sub extends Sup {
int a = 9;
@Override
public void printA() {
System.out.println(a);
}
Sub() {
printA();
}
public static void main(String[] args) {
Sub sub = new Sub();
}
}
result:
console print: 0 9
I know that subclass will first calls the superclass constructor
but ,why is the 0 9
, not 8 9
?
The super keyword is used to call the constructor of its parent class to access the parent's properties and methods. Tip: To understand the "inheritance" concept (parent and child classes) better, read our JavaScript Classes Tutorial.
The base (the superclass) needs to be created first, then you can derive it (the subclass). That's why they called them Parent and Child classes; you can't have a child without a parent. On a technical level, a subclass inherits all the members (fields, methods, nested classes) from its parent.
The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
Super class constructor is always called during construction process and it's guaranteed that super class construction is finished before subclass constructor is called. This is the case for most if not all the object oriented language.
When the Sup
constructor calls printA()
it executes the printA
method of class Sub
(which overrides the method of the same name of class Sup
), so it returns the value of the a
variable of class Sub
, which is still 0
, since the instance variables of Sub
are not yet initialized (they are only initialized after the Sup
constructor is done).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With