在Java中實現介面方法時,能否更改訪問修飾符(從public)?
Java 中的介面是方法原型的規範。每當您需要指導程式設計師或制定一個合同,指定型別的方法和欄位應該如何時,您可以定義一個介面。
要建立此型別的物件,您需要實現此介面,為介面的所有抽象方法提供主體,並獲取實現類的物件。
介面的所有方法都是公共的和抽象的,我們將使用 interface 關鍵字定義介面,如下所示:
interface MyInterface{
public void display();
public void setName(String name);
public void setAge(int age);
}實現介面的方法
在實現/覆蓋方法時,子類/實現類中的方法的訪問限制不能高於超類中的方法。如果您嘗試這樣做,則會引發編譯時異常。
由於 public 是最高的可見性或最低的訪問限制,並且介面的方法預設是 public 的,因此您無法更改修飾符,這樣做意味著增加了訪問限制,這是不允許的,並且會生成編譯時異常。
示例
在下面的示例中,我們透過刪除訪問說明符“public”來繼承介面中的方法。
interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public static int num = 10000;
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:7: error: display() in InterfaceExample cannot implement display() in MyInterface
void display() {
^
attempting to assign weaker access privileges; was public
InterfaceExample.java:14: error: cannot assign a value to final variable num
MyInterface.num = 200;
^
2 errors
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP