“instanceof”运算符对于接口和类的行为不同

问题描述 投票:0回答:3

我想知道 Java 中

instanceof
运算符的以下行为。

interface C {}

class B {}

public class A {
    public static void main(String args[]) {
        B obj = new B();
        System.out.println(obj instanceof A);      //Gives compiler error
        System.out.println(obj instanceof C);      //Gives false as output
    }
}

为什么会这样?

interface C
class B
之间没有关系,但它给出 false,而在
obj instanceof A
的情况下它给出编译器错误?

java class inheritance interface instanceof
3个回答
131
投票

因为 Java 没有多类继承,所以在编译期间绝对知道

obj
类型的对象不能是
B
的子类型。另一方面,它可能是接口
A
的子类型,例如在本例中:

C

因此,仅查看 
interface C {} class B {} class D extends B implements C {} public class A { public static void main(String args[]) { B obj = new D(); System.out.println(obj instanceof C); //compiles and gives true as output } }

表达式编译器无法提前判断它是 true 还是 false,但是查看

obj instanceof C
它知道这始终是 false,因此毫无意义,可以帮助您防止错误。如果您仍然想在程序中进行这种无意义的检查,您可以向
obj instanceof A
:
 添加显式转换

Object



1
投票
System.out.println(((Object)obj) instanceof A); //compiles fine

修饰符,可以保证不存在

final
的子类,该子类可以实现接口
Test
。在这种情况下,很明显
Foobar
Test
彼此不兼容:

Foobar

否则,如果 
public final class Test { public static void main(String[] args) { Test test = new Test(); System.out.println(test instanceof Foobar); // Compiler error: incompatible types } } interface Foobar { }

未声明

Test
,则
final
的子类可能会实现该接口。这就是为什么编译器在这种情况下会允许语句
Test
    


0
投票

test instanceof Foobar

	
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.