在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
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬