interface Read {}
class Student implements Read {}
class Create { private Read read; ... }
Read read = new Create().getRead(); // 實際可能為 null 或 Student 實例
read instanceof Student:取決於運行時 read 指向的實際對象類型。若 setRead(new Student()) 則 true,否則 false。Student stu = (Student) read;:編譯通過(接口可轉換為任意實現類),運行時若實際類型不是 Student 或其子類,拋 ClassCastException。if (read instanceof Student) {
Student stu = (Student) read; // 安全轉換
// 使用 stu 特有方法
}
盡量面向接口編程,避免下行轉型;若必須用實現類特有功能,考慮在接口中定義默認方法或用訪問者模式。