在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 教师闺蜜祝福语简短