[英]Instanceof does not show compile error with interface, but with abstract class does
I think the title is self explanatory. 我认为标题是不言自明的。 So suppose I have this code: 因此,假设我有以下代码:
interface A { }
abstract class B { }
class C { }
C c = new C();
System.out.println(c instanceof A); //fine
System.out.println(c instanceof B); // compile error
In a comment from the question I read this: 在这个问题的评论中,我读到:
The compiler can never know whether a given type doesn't implement an interface because a potential subclass could implement it. 编译器永远无法知道给定类型是否未实现接口,因为潜在的子类可以实现该接口。
So if for interface
this works, why it should not work for an abstract class
? 因此,如果对于interface
此方法有效,那么为什么它对abstract class
不起作用? It also should be extended by some other class, as it can't exist by it's own. 它也应该由其他类进行扩展,因为它本身不能存在。 Can someone clarify this? 有人可以澄清吗?
Update Compile message: 更新编译消息:
Error:(22, 28) java: incompatible types: C cannot be converted to B 错误:(22、28)Java:不兼容的类型:C无法转换为B
It is simple: C extends Object. 很简单:C扩展了Object。 No subclass of C could possible extend B. You can't add another base class, because Java doesn't support multiple inheritance. C的任何子类都不能扩展B。您不能添加另一个基类,因为Java不支持多重继承。
Whereas a subclass of C can very well implement that additional interface. 而C的子类可以很好地实现该附加接口。 But there is simply no way how a C object could also be a B instance. 但是根本无法将C对象也变成B实例。
So: 所以:
D extends C implements B // obviously all fine
whereas 而
D extends B extends C
is impossible. 是不可能的。 Because B is already defined to not extend anything but Object. 因为B 已经定义为除了Object之外不扩展任何东西。 Of course, the "trick" here is that both classes B, C are both known, and as said: C isn't extending B. 当然,这里的“技巧”是,类B,C都是已知的,并且如前所述:C不是扩展B。
Take for example 举个例子
class D extends C implements A{}
C c = new D();
The compiler can immediately tell that c
can never refer to an instance of B
because if a class extends C
it cannot extend B
also. 编译器可以立即告诉c
永远不能引用B
的实例,因为如果类扩展了C
那么它也不能扩展B
As the above example shows, the same cannot be said of interfaces. 如以上示例所示,接口不能说相同。
That is because it's strictly impossible to create instances of an abstract class in java. 那是因为在Java中创建抽象类的实例是绝对不可能的。 The operator instanceof is called from class Object and cannot be called if there is no instance of a class that revoked it (object). 运算符instanceof是从Object类调用的,如果没有撤销它的类的实例(对象),则不能调用该运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.