简体   繁体   English

在 Java 中使用 instanceof 时,实现 class 的接口返回值为真

[英]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.我是自学的 Java,我对在 Java 中使用“instanceof”有点困惑。 Basically I know to use instanceof, however I'm having a hard time with this case.基本上我知道要使用 instanceof,但是我很难处理这种情况。 I write an interface, then use a class to implement that interface.我编写了一个接口,然后使用 class 来实现该接口。 Next I want to check if the interface has instanceof with the implementing class.接下来,我想检查接口是否具有实现 class 的 instanceof。 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.你不能创建接口的object,因为接口基本上是一个完整的抽象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因此,如果我们没有任何方法的实现,那么这意味着如果我们创建该接口的 object 并调用该方法,它不会编译任何代码,因为没有要编译的代码

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. A implement Demo等: object with type A instanceof Demo将是true ,但反之则不然。

Ideally, Demo knows nothing about A .理想情况下, DemoA一无所知。

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 . result为假,因为demo不是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 .因为A实现了Demo ,所以A的所有实例在被检查为Demo时都会返回 true 。

You can define demo to be an instance of A and then check if it is an instance of Demo :您可以将demo定义为A的实例,然后检查它是否是Demo的实例:

A demo = new A();

boolean result = demo instanceof Demo; // now it is true
System.out.println(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM