简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM