Can we create an object of an interface?

我只是一个虾纸丫 提交于 2019-11-26 14:16:29
jjnguy

What you are seeing here is an anonymous inner class:

Given the following interface:

interface Inter {
    public String getString();
}

You can create something like an instance of it like so:

Inter instance = new Inter() {
    @Override
    public String getString() { 
      return "HI"; 
    } 
  };

Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.

test should be the output. This is an example of an anonymous inner class.

This is a very common pattern used with the Comparator interface as an emulation of closures.

The trick is not exactly about the annonymous inner class, this prints test cause it overrides the toString method and while System.out.println a Object it implicit call it's toString method.

Kshitij

Try this too... The name of annonymous class is generated!

Inter instance = new Inter() {
    public String getString(){ return "HI"+this.getClass(); }
};
Abhijit Chakra

I don't know the significance of this question. If this is an interview question, then I can say it's okay. But in real time it's not the right approach to implement an inheritance.So coming to the answer of the question, here what you are doing is an anonymous inner class .

Here you are instantiating a class and implementing the inheritance by writing,

System.out.println(new TestA() {
    public String toString() {
        return “test”;
    }
}); 

and ofcourse the result would be test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!