看看我是誰–Java instanceof 那些事兒

來源:互聯網
上載者:User

長輩們常說:人啊,什麼時候都不能夠忘本。

經過上兩篇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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.