why only Abstract class can have constructor but Interface cannot, while I can create obj of both via Annonymous approach

huangapple go评论84阅读模式
英文:

why only Abstract class can have constructor but Interface cannot, while I can create obj of both via Annonymous approach

问题

我在各个平台上学到,接口(Interface)不能有构造函数,而抽象类(Abstract class)可以有。一个不能在接口中拥有构造函数的原因是因为类的所有非静态变量可以在构造函数中进行初始化,而在接口中我们只能拥有静态变量,而且这些变量只能在声明时进行初始化。

还有其他的原因可以解释这个需求吗?因为通过匿名类(Anonymous class)对象的创建,我可以创建接口和抽象类的对象。并且我可以在创建匿名类的同时定义接口中的抽象方法的实现体。

英文:

I studied on various platform that Interface cannot have constructor while abstract class can have. One reason for which we cannot have constructor in our interface is that all non static vars of class can be intitialized into constructor and in Interface we can have only static one that too need to be initialized at time of declrn only.
Any other reason which can justify need to be shared. Because via Annonymous class object creation I can create Object of Interface and Abstract class both. And whatever Abstract methods I have inside my Interface I can define while creating the body of Annonymous.

答案1

得分: 1

从接口new MyInterface() {...}创建对象时,编译器实际上会创建一个实现该接口的匿名类。

接口不允许非静态成员,因此在没有要初始化的内容时构造函数就没有意义。抽象类可以有非静态成员,可以通过构造函数进行初始化,

详细了解匿名类

英文:

When you create an object from interface new MyInterface() {...}, the compiler actually creates an anonymous class that implements the interface.

Interfaces don't allow non-static members, so there is no point in having a constructor when there is nothing to initialize. Abstract classes can have non-static members to be initialized by constructor,

Read more about anonymous classes

huangapple
  • 本文由 发表于 2020年10月15日 00:45:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64357968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定