看书的时候看到一道例题,输出和我想的不一样?不知道为什么,求解释
程序代码为:
public class Test {
public static void main(String[] args) {
A a = new A();
}
}
class A extends B{
int i = 5;
static int j = 4;
public A() {
// TODO Auto-generated constructor stub
System.out.println("From A'constructor i is " + i);
System.out.println("From A'constructor j is " + j);
}
void m(){
System.out.println("From A's method i is " + i);
System.out.println("From A's method j is " + j);
}
}
class B {
public B() {
// TODO Auto-generated constructor stub
m();
}
void m(){
System.out.println("From B");
}
}
输出结果是:
From A's method i is 0
From A's method j is 4
From constructor i is 5
From constructor j is 4
From A's method j is 4
From constructor i is 5
From constructor j is 4
A继承B,所以A中m()方法覆盖了B中m()方法,所以实例化A对象a时,调用A的构造函数,首先默认调用了B的无参构造函数,B的无参构造函数调用了m()方法,由于多态性,此时调用的方法是A类中定义的m()方法,输出i和j静态的值,由于i是实例变量,此时为实例化,所以默认i是0,而j是静态变量,所以在A类装载的时候就已经初始化,所以i=0,j=4。接着调用A的构造方法,实例变量i被初始化为5,j仍然是4。