(原)java 向上转型中,任何域的访问操作都是由编译器解析,不是多态
最近在向java发力,学习学习了下。看到了多态这一节,书中有个比较好的例子,所以就准备写下来,记录下来:
1 package dynamic_binding01; 2 3 public class dynamic_binding01 { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Super super1=new Sub(); 8 System.out.println("sup.field="+super1.field+",sup.getField="+super1.getField()); 9 Sub sub=new Sub(); 10 System.out.println("sub.field="+sub.field + ",sub.getField="+sub.getField() + ",sub.getSuperField="+sub.getSuperField()); 11 12 } 13 14 } 15 16 class Super{ 17 public int field=0; 18 public int getField(){ 19 //System.out.println("Super class getField"); 20 return field; 21 } 22 } 23 24 class Sub extends Super{ 25 public int field=1; 26 public int getField(){ 27 //System.out.println("Sub class getField"); 28 return field; 29 } 30 public int getSuperField(){ 31 //System.out.println("Sub class getSuperField"); 32 return super.field; 33 } 34 }
运行结果为:
1 sup.field=0,sup.getField=1 2 sub.field=1,sub.getField=1,sub.getSuperField=0
总结:子类在向上转型为父类后,任何域的访问操作都是由编译器进行绑定的,所以不是多态的。