說白了就是強制轉(zhuǎn)換,用父類的類型來操作子類的指針,因此調(diào)用范圍會限制在父類中,但是調(diào)用的是子類實現(xiàn)的方法
package?com.java.Obj; public?class????Obj?{ ????public??void?Test() ????{ ????????System.out.println("Obj?Test"); ????} }
package?com.java.Obj; public?class?Sub1?extends?Obj?{ ????public??void?Test() ????{ ????????System.out.println("Sub1?Test"); ????} }
package?com.java.Obj; public?class?Sub2?extends?Obj?{ ????public??void?Test() ????{ ????????System.out.println("Sub2?Test"); ????} }
import?com.java.Obj.Obj; import?com.java.Obj.Sub1; import?com.java.Obj.Sub2; public?class?Test11A?????{ ?????public?void???check(Obj??j)?{ ?????????j.Test(); ????} ????public?static?void?main(String[]?args)?{ ????????//?TODO?自動生成的方法存根 ????????Test11A?test11a?=?new?Test11A(); ????????Obj?obj?=?new?Sub1();? ????????Obj?obj2?=?new?Sub2();?? ????????test11a.check(obj);//調(diào)用子類的實現(xiàn) ????????test11a.check(obj2);//調(diào)用子類的實現(xiàn) ????????System.out.println("hello"); ????}