Why can't we instantiate an interface or an abstract class in java without an anonymous class method?

自闭症网瘾萝莉.ら 提交于 2019-11-27 05:47:53

问题


I know, we can not instantiate either an interface or an abstract class in java except using anonymous class method but what is the reason behind it?


回答1:


You can't instantiate an interface or an abstract class because it would defy the object oriented model.

Interfaces represent contracts - the promise that the implementer of an interface will be able to do all these things, fulfill the contract.

Abstract classes are a similar idea, in that they represent an unfulfilled contract, a promise to be able to do things, except unlike interfaces they have some of their functions or fields defined but need filling in before they can used.

Simply, in a good object oriented program, you should never want to instantiate an abstract class or interface. If you do, the design is probably wrong.

(Anonymous classes are actually non-abstract instantiations, just that they don't need to be given a name, so they appear to be 'raw interfaces' but they're actually an implementation of the interface that has no name. That's my understanding, at least.)




回答2:


Here is a basic explanation without deeper concept.

  • Interface has no method implemented, so there is no purpose to instantiate it as 'nothing' will happen when invoke a method
  • Abstract class can have abstract method declaration, which is like a interface method with no implementation.



回答3:


You can't instantiate interfaces or abstract classes because some of their methods might not have any definitions.



来源:https://stackoverflow.com/questions/17077547/why-cant-we-instantiate-an-interface-or-an-abstract-class-in-java-without-an-an

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