我只是在尝试一些示例代码来检查 Java 中的类变量覆盖行为。下面是代码:
class A{
int i=0;
void sayHi(){
System.out.println("Hi From A");
}
}
class B extends A{
int i=2;
void sayHi(){
System.out.println("Hi From B");
}
}
public class HelloWorld {
public static void main(String[] args) {
A a= new B();
System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B
a.sayHi(); // method from B gets called since object is of type B
}
}
我无法理解下面这两行发生了什么
System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B
为什么即使对象是 B
类型,a.i
也会打印 0
?为什么在将其转换为 B
后打印 2
?
最佳答案
i
不是方法 - 它是数据成员。数据成员不会覆盖,它们隐藏。因此,即使您的实例是 B
, 它有两个数据成员 - i
来自 A
和 i
来自 B
.当您通过 A
引用它时引用你会得到前者,当你使用 B
时引用(例如,通过显式转换它),你会得到后者。
实例方法,另一方面,表现不同。不管引用的类型如何,因为实例是 B
例如,您将获得多态行为并获得字符串 "Hi From B"
打印出来。
关于java - Java中的方法覆盖与类变量覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30558552/