[英]why interface and abstract methods can't be instantiated?
I am unable to figure out why instantiation of interface and abstract class is restricted in java. 我无法弄清楚为什么在java中限制接口和抽象类的实例化。 I know reference for implementation of interface and abstract class can be created.
我知道可以创建接口和抽象类的实现参考。 I am clear about that, but why it can't be instantiated?
我很清楚,但为什么它不能被实例化? Anyone please help me
有人请帮助我
The point of both an interface and an abstract class is to provide an API which has to be implemented in a concrete class. 接口和抽象类的要点是提供必须在具体类中实现的API。
For example, suppose I declare this interface: 例如,假设我声明了这个接口:
public interface Foo
{
int bar();
}
And imagine if this were valid code: 想象一下,如果这是有效的代码:
Foo foo = new Foo();
int x = foo.bar();
What could the value of x
be? x
的价值是什么? We haven't specified an implementation of bar
anywhere. 我们没有在任何地方指定
bar
的实现。 It's a meaningless call, without a real implementation to back it up. 这是一个毫无意义的电话,没有真正的实施来支持它。
the If you think of a class as blueprints for creating (instantiating) an instance, much like the blueprints for a house tell you how to build a house. 如果你认为一个类是创建(实例化)实例的蓝图,就像房子的蓝图告诉你如何建造一个房子。 Think of an interface as a floorplan for the house - its an incomplete view (specification) of the house.
将界面视为房屋的平面图 - 它是房屋的不完整视图(规格)。 There isn't enough detail to build the house from it - its only an outline of the rooms.
没有足够的细节来建造房子 - 它只是房间的轮廓。 An abstract method is worse - its just the outline of one room.
抽象方法更糟糕 - 它只是一个房间的轮廓。
Interfaces and Abstract classes are not concrete classes. 接口和抽象类不是具体类。 They are deamed to be incomplete and not to be created.
他们被贬低为不完整而不被创造。 You can use a subclass or implementing class.
您可以使用子类或实现类。
An Abstract class is a class that is not fully implemented. Abstract类是未完全实现的类。 You want to force the developer to implement all the abstract parts of the class BEFORE he/she can instanciate it.
您希望强制开发人员在他/她可以实例化之前实现该类的所有抽象部分。
An Interface is a contract that a class must respect. 接口是类必须遵守的合同。 As such, it cannot be instanciated.
因此,它无法实现。 It can be important to define an Interface that a set of classes must respect in the case of a plugin system for example : All you plugins will share the same interface and thus will be inter-changeable.
例如,在插件系统的情况下定义一组类必须遵守的接口可能很重要:所有插件将共享相同的接口,因此可以互换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.