Java多态之Father f=new Son();
2012 年 6 月 21 日
成员变量静态方法看左边,非静态方法编译看左边,运行看右边。
- 左边Father f其实是定义了一个Father类的对象,而右边new Son()可以只理解为是一个重写了Father类方法的对象。
- 因此,f的成员变量,静态方法都是Father类的,而只有被重写的方法才是调用Son类的。
-
所以编译看左边指的是如果调用Son类的特有方法的话会编译错误,因为这个 被重写的Father类
里并没有这个Son类的特有方法。
class Father{ int a=1; static int b=2; void say(){ System.out.println("I am father"); } void ffun(){ System.out.println("father's function"); } static void fun(){ System.out.println("static father"); } } class Son extends Father{ int a=3; static int b=4; void say(){ System.out.println("I am son"); } void sfun(){ System.out.println("son's function"); } static void fun(){ System.out.println("static son"); } } public class Polymorphism1 { public static void main(String[] args) { Father a=new Son(); a.say(); a.ffun(); System.out.println(a.a); Father b=new Father(); b.say(); b.ffun(); System.out.println(b.a); Son c=new Son(); c.say(); c.sfun(); System.out.println(c.a); System.out.println(Father.b); System.out.println(Son.b); Father.fun(); Son.fun(); } }