Why Java interface can be instantiated in these codes? [duplicate]

佐手、 提交于 2019-12-01 10:37:41
Pau Kiat Wee

That code does not instantiate an interface, but rather an anonymous class which implements ActionListener or Runnable.

An anonymous class is a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator.

The code is creating an instance of ActionListener anonymously, which means the class does not actually have any name.

After compiling that class, you can see a class YourClass$1.class in the output. The $1 simply means that class is an anonymous class and the number 1 is generated by the compiler. When you have two anonymous classes, it will have something like YourClass$1.class and YourClass$2.class in the compiled classes.

See

Above example does not create new instance of interface - after new keyword there is implementation method for current interface. Read more about anonymous class.

This form is just a shorthand to make it easier to create an object that implements an Interface. It's not the interface itself being instantiated, but rather an Object implements Runnable for example.

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