如何透過 Java 中的介面物件訪問派生類成員變數?
當您嘗試用子類物件儲存超類的引用變數時,只能使用此物件訪問超類的成員,如果您嘗試使用此引用訪問派生類的成員,則會收到編譯時錯誤。
示例
interface Sample {
void demoMethod1();
}
public class InterfaceExample implements Sample {
public void display() {
System.out.println("This ia a method of the sub class");
}
public void demoMethod1() {
System.out.println("This is demo method-1");
}
public static void main(String args[]) {
Sample obj = new InterfaceExample();
obj.demoMethod1();
obj.display();
}
}輸出
InterfaceExample.java:14: error: cannot find symbol obj.display(); ^ symbol: method display() location: variable obj of type Sample 1 error
如果您需要使用超類的引用訪問派生類的成員,則需要使用引用運算子轉換引用。
示例
interface Sample {
void demoMethod1();
}
public class InterfaceExample implements Sample{
public void display() {
System.out.println("This is a method of the sub class");
}
public void demoMethod1() {
System.out.println("This is demo method-1");
}
public static void main(String args[]) {
Sample obj = new InterfaceExample();
obj.demoMethod1();
((InterfaceExample) obj).display();
}
}輸出
This is demo method-1 This is a method of the sub class
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP