instanceof及類型轉換


instanceof

instanceof是Java中的二元運算符,

左邊是對象,右邊是類;

當對象是右邊類或子類或間接子類所創建對象時,返回true;否則,返回false。

//Teacher和Student繼承Person 
//Object>String
//Object>Person>Teacher
//Object>Person>Studnet
Object object = new Student();
        System.out.println(object instanceof Student);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Object);//true
        System.out.println(object instanceof Teacher);//false
        System.out.println(object instanceof String);//false
        System.out.println("=======================");
        Person person = new Student();
        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        System.out.println(person instanceof Teacher);//false
//        System.out.println(person instanceof String);//編譯錯誤
        System.out.println("=======================");
        Student student = new Student();
        System.out.println(student instanceof Student);//true
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Object);//true
//        System.out.println(student instanceof Teacher);//編譯錯誤
//        System.out.println(student instanceof String);//編譯錯誤

 

 

 

 

數據類型轉換

1.基本數據類型轉換:

byte,short,char<int <long<float<double

由低到高自動轉換byte--->double 自動

由高到低強制轉換double--->byte 強制

2.引用數據類型

子類<父類

student<person<object

由低到高,自動轉換student---->object 自動

由高到低,強制轉換object---->student 強制

子類轉父類,自動動轉換,但會丟失子類的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM