问题
I was just trying some sample code for checking class variable overriding behavior in Java. Below is the code:
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
}
}
I am not able to understand whats happening at these two lines below
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
Why does a.i
print 0
even if the object is of type B
? And why does it print 2
after casting it to B
?
回答1:
i
is not a method - it's a data member. Data members don't override, they hide. So even though your instance is a B
, it has two data members - i
from A
and i
from B
. When you reference it through an A
reference you will get the former and when you use a B
reference (e.g., by explicitly casting it), you'll get the latter.
Instance methods, on the other hand, behave differently. Regardless of the the type of the reference, since the instance is a B
instance, you'll get the polymorphic behavior and get the string "Hi From B"
printed.
回答2:
Even though A is initialized as new B(), the variable is an A. if you say
B a = new B();
you won't have that problem.
来源:https://stackoverflow.com/questions/30558552/method-overriding-vs-class-variable-overriding-in-java