java中如何用instanceof判断接口
在Java中,可使用instanceof关键字来判断一个对象是否是实现了某个接口。下面是一个示例:
interface MyInterface {
// 接口方法
void myMethod();
}
class MyClass implements MyInterface {
// 实现接口方法
public void myMethod() {
System.out.println("MyClass 实现了 MyInterface 接口");
}
}
class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
// 使用 instanceof 判断对象是否是实现了接口
if (obj instanceof MyInterface) {
System.out.println("obj 是 MyInterface 的实例");
} else {
System.out.println("obj 不是 MyInterface 的实例");
}
}
}
输出结果:
obj 是 MyInterface 的实例
在这个示例中,MyClass类实现了MyInterface接口,并且通过instanceof判断obj对象是否是是MyInterface的实例。由于obj是由MyClass类创建的,也就是MyClass类的一个实例,同时也实现了MyInterface接口,因此obj被判断为MyInterface的实例,输出结果为"obj 是 MyInterface 的实例"。
TOP