在 Java 中從一個實現類中訪問兩個具有相同介面的變數?
介面在 Java 中類似於類,但是,它僅包含抽象方法和最終且為靜態的欄位。
你可以使用 Java 中的單個類實現多個介面。只要兩個介面具有相同名稱,由於介面的所有欄位預設情況下都是靜態的,所以你可以使用介面名稱來訪問它們,如下所示 −
示例
interface MyInterface1{
public static int num = 100;
public void display();
}
interface MyInterface2{
public static int num = 1000;
public void show();
}
public class InterfaceExample implements MyInterface1, MyInterface2{
public static int num = 10000;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
System.out.println("num field of the interface MyInterface1"+MyInterface1.num);
System.out.println("num field of the interface MyInterface2"+MyInterface2.num);
System.out.println("num field of the class InterfaceExample "+obj.num);
}
}輸出
num field of the interface MyInterface1 100 num field of the interface MyInterface2 1000 num field of the class InterfaceExample 10000
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP