如何在 Java 中從類中隱藏不受支援的介面方法?
實際上你不能。一旦你實現了某個介面,就必須為其實現所有方法,或將類設為抽象類。如果不實現方法(除非這些方法是預設方法),則無法跳過某個介面中的方法。儘管如此,如果你嘗試跳過某個介面中的實現方法,則會生成一個編譯時錯誤。
示例
interface MyInterface{
public static int num = 100;
public void sample();
public void getDetails();
public void setNumber(int num);
public void setString(String data);
}
public class InterfaceExample implements MyInterface{
public static int num = 10000;
public void sample() {
System.out.println("This is the implementation of the sample method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.sample();
}
}輸出
編譯時錯誤
InterfaceExample.java:8: error: InterfaceExample is not abstract and does not override abstract method setString(String) in MyInterface
public class InterfaceExample implements MyInterface{
^
1 error但是,你可以實現這些不需要的/不受支援的方法,並向它們丟擲異常,如 UnsupportedOperationException 或 IllegalStateException。
示例
interface MyInterface{
public void sample();
public void getDetails();
public void setNumber(int num);
public void setString(String data);
}
public class InterfaceExample implements MyInterface{
public void getDetails() {
try {
throw new UnsupportedOperationException();
}
catch(UnsupportedOperationException ex) {
System.out.println("Method not supported");
}
}
public void setNumber(int num) {
try {
throw new UnsupportedOperationException();
}
catch(UnsupportedOperationException ex) {
System.out.println("Method not supported");
}
}
public void setString(String data) {
try {
throw new UnsupportedOperationException();
}
catch(UnsupportedOperationException ex) {
System.out.println("Method not supported");
}
}
public void sample() {
System.out.println("This is the implementation of the sample method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.sample();
obj.getDetails();
obj.setNumber(21);
obj.setString("data");
}
}輸出
This is the implementation of the sample method Method not supported Method not supported Method not supported
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP