【发布时间】:2023-03-24 08:23:01
【问题描述】:
请看一下这段代码:
class Foo {
public int a;
public Foo() {
a = 3;
}
public void addFive() {
a += 5;
}
public int getA() {
System.out.println("we are here in base class!");
return a;
}
}
public class Polymorphism extends Foo{
public int a;
public Poylmorphism() {
a = 5;
}
public void addFive() {
System.out.println("we are here !" + a);
a += 5;
}
public int getA() {
System.out.println("we are here in sub class!");
return a;
}
public static void main(String [] main) {
Foo f = new Polymorphism();
f.addFive();
System.out.println(f.getA());
System.out.println(f.a);
}
}
这里我们将Polymorphism 类的对象的引用分配给Foo 类型的变量,经典多态。现在我们调用方法addFive,它已在类Polymorphism 中被覆盖。然后我们从一个 getter 方法打印变量值,该方法在类多态性中也被覆盖。所以我们得到答案为 10。但是当公共变量 a 被 SOP 化时,我们得到答案 3!!
这是怎么发生的?即使引用变量类型是 Foo 但它指的是多态类的对象。那么为什么访问f.a 不会导致Polymorphism 类中的a 值被打印出来呢?请帮忙
【问题讨论】:
标签: java polymorphism