public class Test { public static void main(String[] args) { A a = new A(); a.s = 11; B b = new B(); b.s = 22; a = b; System.out.println(a.s); System.out.println(b.s); System.out.println(a.getS()); System.out.println(b.getS()); } } class A { int s = 1 ; int getS() { return s; } } class B extends A { int s = 0; int getS() { return s; } }
输出的是 1 22 22 22
为什么 第一个输出的是1而不是0或者22.按照输出1来看,他调用的是父类A的成员变量s。
这个涉及到了多态,此时a已经指向了men-B,理应输出22,为何输出的是A的成员变量s=1。
The member variable called is determined by the "type of the variable".
A a;
If the variable is of type A, it is the variable of type A being called.A a;
变量为A类型就是调用的A类型的变量。B b;
变量为B类型就是调用的B类型的变量。多态
是跟method
相关,跟field
B b;
If the variable is of type B, it is the variable of type B being called.Polymorphism
is related tomethod
and has nothing to do withfield
.