class Base {
int count = 10;
public void display() {
System.out.println(this.count);
}
}
class Sub extends Base {
int count = 20;
public void display() {
System.out.println(this.count);
}
}
public class FieldMethodTest {
public static void main(String[] args){
Sub s = new Sub();
System.out.println(s.count);// 20
s.display();// 20
Base b = s;
System.out.println(b == s); // true 此时b和s指向同一个new sub()地址值
System.out.println(b.count);// 10 属性,编译运行都看左边
b.display();// 运行看右边 b = new Sub().display() 20
Base b1 = new Base();
System.out.println(b1.count); // 10
b1.display();// 10
}
}
总结:
- 实例b == s,此时b和s指向同一个new Sub()地址值
- 属性和static方法,编译和运行都只看左边
即:b.count(),运行时看左边<==>b = new Base().count = 20;- 方法:编译看左边,运行看右边.
即:b.display(),运行时看右边<==>b = new Sub().display() = 10;