class Parent
{
public void test()
{
System.out.println("the father's test");
}
public Parent()
{
System.out.println("It's father");
test();
}
}
public class Child extends Parent
{ public static void main(String[] args)
{
//new Parent();
//System.out.println();
Child c= new Child();
}
private int instanceValue = 20;
public Child()
{
test();
}
public void test()
{
System.out.println("the Chind instance value is: " +instanceValue);
}
}
输出结果:
It's father
the Chind instance value is:0
the Chind instance value is:20
这个不是虚函数吧?
为什么在调用父类的构造函数时调用的test()是子类中的test()方法?
在进行子类实例化的时候,他先去调用父类的构造函数,而在程序里,父类的构造函数里有一个test方法,其实这个是被子类的实例对象调用的,并非是父类的,因为父类根本就没有做任何实例化的动作,根本不可能调用自身的test的方法。我理解的是在编译的时候,子类继承父类的那些属性和方法就已经加入到了子类的文件中,所以虽然是父类的方法调用的子类的方法,但实际上还是子类的对象调用的,所以被调用的还是子类的方法,而不是父类的。
不知道这样理解是不是正确。。。