在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("这是sample方法的实现");
}
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("这是sample方法的实现");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.sample();
obj.getDetails();
obj.setNumber(21);
obj.setString("data");
}
}输出结果
这是sample方法的实现 Method not supported Method not supported Method not supported
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志