1.重温JAVA语法:如父类Father与子类Son:
class Son extends Father{
public String name = "son";
public void say(){
System.out.println("i am " + this.name);
}
public static void main(String[] args){
Father f = new Father();
System.out.println("Father f = new Father() : f.name => " + f.name);
System.out.print("Father f = new Father() : f.say() => ");
f.say();
Father fa = new Son();
System.out.println("Father fa = new Son() : fa.name => " + fa.name);
System.out.print("Father fa = new Son() : fa.say() => ");
fa.say();
Son son = new Son();
System.out.println("Son son = new Son() : son.name => " + son.name);
System.out.print("Son son = new Son() : son.say() => ");
son.say();
}
}
输出结果为:
Father f = new Father() : f.name => father
Father f = new Father() : f.say() => i am father
Father fa = new Son() : fa.name => father
Father fa = new Son() : fa.say() => i am son
Son son = new Son() : son.name => son
Son son = new Son() : son.say() => i am son
由此可见,当子类与父类具有同样的成员属性(public)与方法(public)时,父类变量引用子类对象时,
a.父类变量调用成员属性时,子类成员属性不会覆盖父类成员属性,不具动态性;
b.父类变量调用方法时,子类方法将会覆盖父类方法,具有动态性。
为何会如此,目前不明白,还请知道的朋友赐教。