如何在 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