我正在尝试根据instanceof
链接了解Java中的运算符:-instanceof
但是当我尝试运行他们的以下代码时: -
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
我在编译时收到以下错误:
./Child.java:1: error: cannot find symbol
class Child extends Parent implements MyInterface{
^
symbol: class MyInterface
InstanceOfDemo.java:9: error: cannot find symbol
System.out.println("obj1 instanceOf MyInterface" + (obj1 instanceof MyInterface));
^
symbol: class MyInterface
location: class InstanceOfDemo
InstanceOfDemo.java:12: error: cannot find symbol
System.out.println("obj1 instanceOf MyInterface" + (obj2 instanceof MyInterface ));
^
symbol: class MyInterface
location: class InstanceOfDemo
3 errors
下面是放置src代码的目录结构:-
-rw-rw-r-- 1 ankit ankit 174 Oct 25 15:36 Child.class
-rw-rw-r-- 1 ankit ankit 31 Oct 25 15:36 Child.java
-rw-rw-r-- 1 ankit ankit 920 Oct 25 15:41 InstanceOfDemo.class
-rw-rw-r-- 1 ankit ankit 637 Oct 25 15:41 InstanceOfDemo.java
-rw-rw-r-- 1 ankit ankit 25 Oct 25 15:20 MyInterface
-rw-rw-r-- 1 ankit ankit 186 Oct 25 15:36 Parent.class
-rw-rw-r-- 1 ankit ankit 16 Oct 25 15:18 Parent.java
注意:我从Child.java
和InstanceOfDemo.java
编译和运行代码中删除了接口实现。
编辑1:-我可以认为instanceof运算符不能与Interfaces一起使用,因为根据Oracle的instanceof运算符的定义如下:-
instanceof 运算符将对象与指定类型进行比较。您可以使用它来测试对象是类的实例、子类的实例还是实现特定接口的类的实例。