長輩們常說:人啊,什麼時候都不能夠忘本。
經過上兩篇this和super的講解,可以讓自己知道什麼調用自己的方法和成員,什麼時候調用父類的方法和成員,那麼對外人來說,如何區分一個對象到底是父類還是某個子類的執行個體呢?Java中關鍵字instanceof是專門為此而生的。當一個子類的執行個體賦值給一個父類的變數,這是Java多態的一種表現。而有時我們又想知道它到底是誰。
在this那一講有個父類叫Student,super那一講加了一個子類叫ClassLeader,今天在加一個子類叫生活委員吧,Lifeleader。Chinese英語只為做demo,勿怪。
public class LifeLeader extends Student{private int fare;public LifeLeader(String name,String college,int fare){super(name,college);this.fare = fare;}public void print(){super.print();System.out.println("fare is " + fare);}public static void main(String[] args){Student linc = new LifeLeader("linc","shenyang",500);Student lily = new ClassLeader("class monitor","lily","shenyang");whoAreYou(linc);whoAreYou(lily);}public static void whoAreYou(Student student){if(student instanceof ClassLeader){System.out.println("this is ClassLeader!");student.print();}else if(student instanceof LifeLeader){System.out.println("this is LifeLeader!");student.print();}}}
編譯運行:
D:\workspace\Java\project261\instance>javac -d . *javaD:\workspace\Java\project261\instance>java LifeLeaderconstructthis student name is lincthis student name is linc college is shenyangconstructthis student name is lilythis student name is lily college is shenyangthis is LifeLeader!name is: linc age is: 20 college is: shenyangfare is 500this is ClassLeader!name is: lily age is: 20 college is: shenyangduty is class monitor