首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 接口與實現類對象的 instanceof 與強轉規則

     編輯:程式設計疑難解答

代碼場景

interface Read {}
class Student implements Read {}
class Create { private Read read; ... }

Read read = new Create().getRead(); // 實際可能為 null 或 Student 實例

規則總結

  1. read instanceof Student:取決於運行時 read 指向的實際對象類型。若 setRead(new Student()) 則 true,否則 false。
  2. Student stu = (Student) read;:編譯通過(接口可轉換為任意實現類),運行時若實際類型不是 Student 或其子類,拋 ClassCastException。

最佳實踐

if (read instanceof Student) {
    Student stu = (Student) read; // 安全轉換
    // 使用 stu 特有方法
}

設計建議

盡量面向接口編程,避免下行轉型;若必須用實現類特有功能,考慮在接口中定義默認方法或用訪問者模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved