andy.hu :
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
?
Eran :
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).
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=444347&siteId=1