【发布时间】:2019-07-11 12:45:42
【问题描述】:
我正在学习后期绑定和静态绑定。现在我对这些代码感到困惑。
这是我的分析:
-
hello()是非静态方法,所以我们应该使用动态绑定,即 Child。 - 但是子类中没有
hello()方法,所以转到它的超类。找到hello(),打印第一行“Hello from parent call calssMethod”。 - 由于
classMethod()是静态的,所以我们应该使用c的静态绑定,也就是Child。所以输出是“classMethod in Child”。
所以输出应该是
来自父调用 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() 方法设为静态会怎样?
【问题讨论】:
-
如果您想要不同的结果,只需覆盖该方法。我认为您并没有真正理解“静态”是什么以及它的用途。
标签: java binding static polymorphism