我正在学习后期绑定和静态绑定。现在我对这些代码感到困惑。
这是我的分析:
hello()是非静态方法,所以我们应该使用动态绑定,即Child。
但是子类里面没有hello()方法,就去它的父类。查找hello()并打印第一行“Hello from parent call calssMethod”。
由于classMethod()是静态的,所以我们应该使用c的静态绑定,也就是Child。所以输出是“child 中的 classMethod”。
所以输出应该是
来自父调用 calssMethod 的问候
子类中的类方法
class Parent{
public static void classMethod() {
System.out.println("classMethod in Parent");
}
public void instanceMethod() {
System.out.println("InstanceMethod in Parent");
}
public void hello() {
System.out.println("Hello from parent call calssMethod");
classMethod();
}
}
class Child extends Parent{
public static void classMethod() {
System.out.println("classMethod in Child");
}
public void instanceMethod() {
System.out.println("InstanceMethod in Child");
}
}
public class AA {
public static void main(String[] args) {
Child c = new Child();
c.hello();
}
}
现在,问题来了。IDE 显示输出为:
来自父调用 calssMethod 的问候
父类中的类方法
什么是正确的分析过程?
如果我将hello()方法设为静态怎么办?
www说
不负相思意
相关分类