如何在Java中訪問介面的欄位?


Java中的介面是方法原型的規範。無論何時您需要指導程式設計師或制定一個合同,指定某個型別的欄位和方法應該如何,您都可以定義一個介面。預設情況下,

  • 所有成員(方法和欄位)都是公共的

  • 介面中的所有方法都是公共的抽象的(靜態和預設方法除外)。

  • 介面的所有欄位預設情況下都是公共的靜態的最終的

如果您宣告/定義欄位時沒有使用public、static、final或全部三個修飾符,Java編譯器會為您新增它們。

示例

在下面的Java程式中,我們有一個沒有public、static或final修飾符的欄位。

public interface MyInterface{
   int num =40;
   void demo();
}

如果您使用如下所示的javac命令編譯它:

c:\Examples>javac MyInterface.java

它將被編譯而不會出現錯誤。但是,如果您使用如下所示的javap命令驗證編譯後的介面:

c:\Examples>javap MyInterface
Compiled from "MyInterface.java"
public interface MyInterface {
   public static final int num;
   public abstract void demo();
}

訪問介面的欄位

通常,要建立介面型別物件,您需要實現它併為其中的所有抽象方法提供實現。當您這樣做時,介面的所有欄位都會被實現類繼承,即介面欄位的副本在實現它的類中可用。

由於介面的所有欄位預設情況下都是靜態的,因此您可以使用介面名稱訪問它們,如下所示:

示例

 線上演示

interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   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("Value of num of the interface "+MyInterface.num);
      System.out.println("Value of num of the class "+obj.num);
   }
}

輸出

Value of num of the interface 100
Value of num of the class 10000

但是,由於介面的變數是final的,因此您無法重新為它們分配值。如果您嘗試這樣做,將生成編譯時錯誤。

示例

 線上演示

interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   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[]) {
      MyInterface.num = 200;
   }
}

輸出

編譯時錯誤

InterfaceExample.java:14: error: cannot assign a value to final variable num
   MyInterface.num = 200;
               ^
1 error

更新於: 2019年9月6日

13K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告