参见英文答案 > What is the ‘instanceof’ operator used for in Java? 15个
对不起,发布时我犯了一个错误.在这种情况下,实现I的类应该是B而不是A.在这里,我发现令人困惑的地方.
此外,如果C类实现I而不是A或B,结果仍然相同.
interface I{}
public class A{
A() {
System.out.print("A: " + (this instanceof I) + " ");
}
public static void main(String[] args) {
new C();
}
}
class B extends A implements I {
B() {
System.out.print("B: " + (this instanceof I) + " ");
}
}
class C extends B {
C() {
System.out.print("C: " + (this instanceof I) + " ");
}
}
使用instanceof时为什么子类和超类都是真的?
这段代码的结果是:
A: true
B: true
C: true
解决方法:
instanceof运算符检查给定对象是否是给定类的sublcass(不一定是真正的子类).这通常意味着您可以将对象强制转换为该类(将视图缩小到该类).
因此,例如,如果我们有一个ArrayList,我们可以将它转换为List,如果我们针对List检查ArrayList,instanceof也将返回true.所以在你的例子当然可以做到
new C() instanceof B // true
new B() instanceof A // true
但是,类也从父母那里继承了这些属性.因此,类C当然也是A的子类,因为它是B的子类,B是A的子类,所以我们得到
new C() instanceof A // true
我们得到的同样适用于接口
new A() instanceof I // true
并通过继承
new B() instanceof I // true
new C() instanceof I // true
实际的例子
看一下下面的例子
public interface CanBark { }
public class Dog implements CanBark { }
public class Pug extends Dog { }
当然帕格是一只狗,因为狗是一个CanBark,帕格也是一个CanBark,我们得到
new Pug() instanceof Dog // true
new Dog() instanceof CanBark // true
new Pug() instanceof CanBark // true
instanceof的详细信息
Java语言规范(§15.20.2)将instanceof运算符的行为定义为
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (07001) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
演员(§15.16)表现得像
[…] or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.
因此,铸造是指(§5.5)中规定的铸造规则.您的具体案例在(§5.5.1)中定义为
If T (target) is an interface type:
If S (source) is not a final class (07005), then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.
Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).
标签:java,interface
来源: https://codeday.me/bug/20190828/1749330.html