日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java-instanceof和类型转换

發布時間:2024/9/27 java 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java-instanceof和类型转换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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 的保留關鍵字。它的作用是測試它左邊的對象是否是它右邊的類的實例,返回 boolean 的數據類型。// 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); // 編譯報錯}}

類型轉換

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) {// 類型之間的轉換 父 > 子// Person 高 Student 低Person obj = new Student(); // obj.go(); //報錯// student將這個對象轉換為Student類型,我們就可以使用Student類型的方法了 // Student student = (Student)obj; // student.go();// 簡寫((Student) obj).go();// 子類轉換為父類,可能丟失自己的本來的一些方法// 低轉高,直接轉換Student student1 = new Student();student1.go();Person person = student1;}} 多態1. 父類的引用指向子類的對象(子類的引用不能指向父類的對象)2. 把子類轉換為父類,向上轉型3. 把父類轉換為子類,向下轉換;強制轉換4. 方便方法的調用,減少重復的代碼,簡潔

https://www.bilibili.com/video/BV12J41137hu?p=72

總結

以上是生活随笔為你收集整理的Java-instanceof和类型转换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。