I’m self-taught Java and I’m a bit confused about using "instanceof" in Java. Basically I know to use instanceof, however I’m having a hard time with this case. I write an interface, then use a class to implement that interface. Next I want to check if the interface has instanceof with the implementing class. I tried but the return value is only "false" but I want it to return "true" how should I write it? Can I achieve that goal ?Is there any sample code or suggestions for me? I would be very grateful and I would appreciate it. Sorry I’m a newbie, thanks.
interface Demo {
}
class A implement Demo {
}
public class Main {
public static void main(String[] args){
Demo demo = new Demo() {};
boolean result = demo instanceof A ; // I want result is "true";
System.out.println(result);
}
}
>Solution :
The code you gave runs perfectly fine. result is false, because demo is not an instance of A. In fact, it is the other way around. Because A implements Demo all instances of A would return true when they are checked to be a Demo.
You can define demo to be an instance of A and then check if it is an instance of Demo:
A demo = new A();
boolean result = demo instanceof Demo; // now it is true
System.out.println(result);