Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return value is true of interface with implementing class when using instanceof in Java

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading