I am trying to learn about instanceof operator in java as per the link :- instanceof
But when i try to run their following code:-
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 {}
I get the following errors at compile time:
./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
Below is the directory structure where the src code is placed:-
-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
Note: I removed the interface implementation from Child.java and InstanceOfDemo.java to compile and run the code.
Edit 1:- can i consider that instanceof operator can't be used with Interfaces because the definiton of instanceof operator as per Oracle is as follows:-
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
MyInterfaceseems to be defined in a different file, and the name of the file isn't evenMyInterface.java. Hence the .class file isn't generated(and therefore isn't being found by the compiler)