为什么这段代码打印的是 20 20 而不是 20 10?
why this code is printing 20 20 instead of 20 10?
package package1;
public class MyClassA {
protected int size;
public MyClassA() {
}
protected int getAge() {
return 10;
}
public int callAge() {
return getAge();
}
}
package package2;
import package1.MyClassA;
public class MyClassB extends MyClassA {
protected int getAge() {
return 20;
}
private int superesult() {
return super.callAge();
}
public static void main(String args[]) {
MyClassB classb = new MyClassB();
System.out.println(classb.getAge());
System.out.println(classb.superesult());
}
}
当我调用 getAge 和 superresult 方法时,我期望 20 10 作为输出,但代码正在打印 20 20。提前致谢。
是polymorphism。您已经在 getAge()
方法中进行了验证。因此,当您调用该方法时,ovverdien 方法始终执行。
The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
简答:你调用 callAge
因为它是在 A
中实现的。但是该方法调用 getAge
被覆盖(因此 Java 遵循实现,就像在 B
中完成的那样)。
更长的版本:
当你打电话时:
classb.superesult();
它将调用super.callAge()
,这意味着classA
的callAge()
被执行了。 callAge()
在他的部分调用 getAge()
但由于对象是 class B
的实例并且 getAge()
被覆盖 , 它 returns 20
.
请注意,如果您调用 super.foo()
,您只会调用 超级 foo。 super
因此 并不意味着你 "alter the context":超级调用产生的所有调用仍然通过对象上的动态绑定解决(和对象仍然是 B
的一个实例)。 foo
所做的所有调用都可以被覆盖(除非这些调用被标记为 final
)。在大多数情况下,这是所需的行为。
这是因为您在子 class 中覆盖了 getAge()
方法。现在 MyClassB classb = new MyClassB();
指向子 class,因此将调用其方法而不是父方法
package package1;
public class MyClassA {
protected int size;
public MyClassA() {
}
protected int getAge() {
return 10;
}
public int callAge() {
return getAge();
}
}
package package2;
import package1.MyClassA;
public class MyClassB extends MyClassA {
protected int getAge() {
return 20;
}
private int superesult() {
return super.callAge();
}
public static void main(String args[]) {
MyClassB classb = new MyClassB();
System.out.println(classb.getAge());
System.out.println(classb.superesult());
}
}
当我调用 getAge 和 superresult 方法时,我期望 20 10 作为输出,但代码正在打印 20 20。提前致谢。
是polymorphism。您已经在 getAge()
方法中进行了验证。因此,当您调用该方法时,ovverdien 方法始终执行。
The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
简答:你调用 callAge
因为它是在 A
中实现的。但是该方法调用 getAge
被覆盖(因此 Java 遵循实现,就像在 B
中完成的那样)。
更长的版本:
当你打电话时:
classb.superesult();
它将调用super.callAge()
,这意味着classA
的callAge()
被执行了。 callAge()
在他的部分调用 getAge()
但由于对象是 class B
的实例并且 getAge()
被覆盖 , 它 returns 20
.
请注意,如果您调用 super.foo()
,您只会调用 超级 foo。 super
因此 并不意味着你 "alter the context":超级调用产生的所有调用仍然通过对象上的动态绑定解决(和对象仍然是 B
的一个实例)。 foo
所做的所有调用都可以被覆盖(除非这些调用被标记为 final
)。在大多数情况下,这是所需的行为。
这是因为您在子 class 中覆盖了 getAge()
方法。现在 MyClassB classb = new MyClassB();
指向子 class,因此将调用其方法而不是父方法