Thoughts on assigning child classes to parent classes and assigning child classes
2014-3 3
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 T138 {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 lines of commented code
33 // System.out.println(t1.b);
If the command is executed, an error is returned.
Because 29 lines of code
29 T1 t1 = t;
Assign the subclass object instance to the parent class object. t1 and t point to the same memory block, but t1 cannot access the subclass field. Therefore, t1 cannot access variable B.