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);
}
}
You can not create object of interface because interface is basically a complete abstract class. That means Interface only have deceleration of method not their implementation. So if we don’t have any implementation of a method then that means if we create object of that interface and call that method it compile nothing as there is no code to compile
interface Demo {
}
class A implements Demo {
}
public class Main
{
public static void main(String[] args){
Demo demo = new A();
boolean result = demo instanceof A ;
System.out.println(result);
}
}
A implement Demo and so:
object with type A instanceof Demo will be true, but not vice versa.
Ideally, Demo knows nothing about A.
And you shouldn't create an instance of interface.
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:
Demo demo = new A();
boolean result = demo instanceof Demo; // now it is true
System.out.println(result);
Edit:
Changed the declaration of demo because of the comment of @Thomas (Thanks!)