对子类赋给父类的思考
2014-12-03
13:57:48
1 /** 2 * @author nlee 3 * @version 1:09:38 PM Dec 3, 2014 4 */ 5 package test; 6 7 public class T extends T1 8 { 9 int b; 10 11 public T(int s1) 12 { 13 super(s1); 14 b = 111; 15 } 16 17 public void fun2() 18 { 19 System.out.println("T===fun2"); 20 } 21 22 public static void main(String[] args) 23 { 24 T t = new T(5); 25 t.fun1(); 26 t.fun2(); 27 System.out.println(t.b); 28 System.out.println(t.a); 29 T1 t1 = t; 30 t1.fun1(); 31 t1.fun2(); 32 System.out.println(t1.a); 33 // System.out.println(t1.b); 34 } 35 } 36 37 class T1 38 { 39 int a; 40 41 public T1(int s) 42 { 43 a = s; 44 } 45 46 public int get() 47 { 48 return a; 49 } 50 51 public void set(int d) 52 { 53 a = d; 54 } 55 56 public void fun1() 57 { 58 System.out.println("T1---fun1"); 59 } 60 61 public void fun2() 62 { 63 System.out.println("T1---fun2"); 64 } 65 }
33行被注释的代码
33 // System.out.println(t1.b);
若执行则会报错。
因为29行代码
29 T1 t1 = t;
将子类对象实例赋给父类对象,t1和t指向是同一内存块,但是t1不能访问子类的字段,因此t1不能访问变量b。