如果我有以下内容:
interface a {
void a_m();
}
interface b {
void b_m();
}
class x implements a, b {
public static void main(String [] args) {
x cx = new x();
System.out.println(cx instanceof a); <-- true
System.out.println(cx instanceof b); <-- true
}
void a_m() {}
void b_m() {}
}
instanceof
运算符将为两者返回 true。
我当然知道getClass()
可以解决问题,但我只是对 instanceof
的用法感到困惑在这里。
在上面的例子中,接口(interface) a 和 b 是不同的,并且必须有一种方法来区分它们(就类 x 而言)。
任何建议都会很好
最佳答案
instanceof
只是检查您是否实际上是某个对象的实例。换句话说,您是否可以被合法指定/强制转换/等成为该类型。
在这种情况下,X 同时实现了 A 和 B,因此它确实是两者的实例。如果您想检查 X,那么您应该执行 instanceof X
,而不是 instanceof A
和 instanceof B
。
不过,不涉及“区分”。 X 是一个 X,如果您愿意,您也可以将其用作 A 或 B,但只有一个对象。当您创建一个 X 时,每个 X必须都可以用作 A、B 和 X。这就是实现接口(interface)的含义。
想象 X 是一座房子。 A 只说“X 必须有前门”,B 说“X 必须有后门”。如果 Y 实现了 A 但没有实现 B,则:
X instanceof A == X has a front door == true
X instanceof B == X has a back door == true
Y instanceof A == Y has a front door == true
Y instanceof B == Y has a back door == false
关于java - 多接口(interface): instanceof cannot differentiate different interfaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141614/