3、多态性是针对方法的,对象的属性不具备多态性。通过引用变量访问对象实例属性时,系统总是试图访问编译时类型所定义的属性,而不是运行时类型所定义的属性。
示例代码:
class Base { public int num = 9; public void base() { System.out.println("Base base()"); } public void info() { System.out.println("Base info()"); } } class Sub extends Base { public String num = "sub class"; public void sub() { System.out.println("Sub sub()"); } public void info() { System.out.println("Sub info()"); } } public class Main { public static void main(String[] args) { Base bc = new Base();// bc编译时类型和运行时类型都是Base bc.base();// 输出:Base base() bc.info();// 输出:Base info() System.out.println(bc.num);// 输出: 9 Sub sc = new Sub();// sc编译时类型和运行时类型都是Sub sc.base();// 输出:Base base() sc.info();// 输出:Sub info() sc.sub();// 输出:Sub sub() System.out.println(sc.num);// 输出:sub class Base polymorphism = new Sub();// polymorphism编译时类型是Base,运行时类型是Sub polymorphism.base();// 输出:Base base() polymorphism.info();// 输出:Sub info() System.out.println(polymorphism.num);// 输出:9 } }
原文地址:http://blog.csdn.net/u011506951/article/details/42522989