java 为什么我们不能在没有匿名类方法的情况下在java中实例化接口或抽象类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17077547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:54:09  来源:igfitidea点击:

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

javaclassinterfaceabstract

提问by Rakmo

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

我知道,除了使用匿名类方法之外,我们不能在 Java 中实例化接口或抽象类,但这背后的原因是什么?

回答by Patashu

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.)

(匿名类实际上是非抽象的实例化,只是它们不需要命名,所以它们看起来是“原始接口”,但它们实际上是没有名称的接口的实现。这是我的理解, 至少。)

回答by fmodos

Here is a basic explanation without deeper concept.

这是一个没有更深层次概念的基本解释。

  • Interfacehas no method implemented, so there is no purpose to instantiate it as 'nothing' will happen when invoke a method
  • Abstractclass can have abstractmethod declaration, which is like a interface method with no implementation.
  • Interface没有实现任何方法,因此没有必要将其实例化,因为调用方法时不会发生“任何事情”
  • Abstract类可以有abstract方法声明,就像一个没有实现的接口方法。

回答by allenwoot

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

您不能实例化接口或抽象类,因为它们的某些方法可能没有任何定义。