我刚刚尝试了一些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
呢?