Java-instanceof和类型转换
生活随笔
收集整理的這篇文章主要介紹了
Java-instanceof和类型转换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
instanceof
public class Person {public void run(){System.out.println("run");} } public class Student extends Person{ } public class Teacher extends Person{ } public class Application {public static void main(String[] args) {// instanceof 是 Java 的保留關(guān)鍵字。它的作用是測試它左邊的對象是否是它右邊的類的實例,返回 boolean 的數(shù)據(jù)類型。// Object > String// Object > Person > Teacher// Object > Person > StudentObject object = new Student();System.out.println(object instanceof Student); // trueSystem.out.println(object instanceof Person); // trueSystem.out.println(object instanceof Object); // trueSystem.out.println(object instanceof Teacher); // falseSystem.out.println(object instanceof String); // falseSystem.out.println("====================================");Person person = new Student();System.out.println(person instanceof Student); // trueSystem.out.println(person instanceof Person); // trueSystem.out.println(person instanceof Object); // trueSystem.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); // trueSystem.out.println(student instanceof Person); // trueSystem.out.println(student instanceof Object); // true // System.out.println(student instanceof Teacher); // 編譯報錯 // System.out.println(student instanceof String); // 編譯報錯}}類型轉(zhuǎn)換
public class Person {public void run(){System.out.println("run");} } public class Student extends Person{public void go(){System.out.println("go");} } public class Teacher extends Person{ } public class Application {public static void main(String[] args) {// 類型之間的轉(zhuǎn)換 父 > 子// Person 高 Student 低Person obj = new Student(); // obj.go(); //報錯// student將這個對象轉(zhuǎn)換為Student類型,我們就可以使用Student類型的方法了 // Student student = (Student)obj; // student.go();// 簡寫((Student) obj).go();// 子類轉(zhuǎn)換為父類,可能丟失自己的本來的一些方法// 低轉(zhuǎn)高,直接轉(zhuǎn)換Student student1 = new Student();student1.go();Person person = student1;}} 多態(tài)1. 父類的引用指向子類的對象(子類的引用不能指向父類的對象)2. 把子類轉(zhuǎn)換為父類,向上轉(zhuǎn)型3. 把父類轉(zhuǎn)換為子類,向下轉(zhuǎn)換;強(qiáng)制轉(zhuǎn)換4. 方便方法的調(diào)用,減少重復(fù)的代碼,簡潔https://www.bilibili.com/video/BV12J41137hu?p=72
總結(jié)
以上是生活随笔為你收集整理的Java-instanceof和类型转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js判断一个字符串 是否存在在另一个字符
- 下一篇: Node.js从零开发Web Serve