I am unable to figure out why instantiation of interface and abstract class is restricted in 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.
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? We haven't specified an implementation of bar
anywhere. 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. 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.
精彩评论