Monday, 1 August 2016

Create object of interface and Abstract class

YES....
we can create the object of an interface / Abstract class.
As per the java specification we are not allowed to create object of interface and abstract class 
directly.but we can do that indirectly with the help of anonymous inner type.

Interface:
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.


Abstract Class:
An Abstract class is a class that can contain abstract methods or concrete methods( methods those have body) or both.
What happens when we try to create object:
We have an interface SampleInt which contains an abstract method.


SampleAbs is the abstract class with a concrete method showSampleAbs().
Now we are trying to create object to the above defined interface and abstract class in the class App

So , as the compiler is not allowing us to create the object to interface and abstract class we can say We can't create object to an interface or abstract class directly .

How to create object to interface and abstract class:

We can create the object to interface or abstract class indirectly by using anonymous inner type.

App class shows creating object to SampleInt and SampleAbs.
By providing anonymous inner class to Abstract class or interface we can say they have intantiated indirectly.
We can call showSampleAbs() by using SampleAbs object sampleAbs aswellas we can callsampleIntMethod() defined in interface by using it's instance sampleInt.

Calling methods defined inside anonymous type:
Suppose we have defined some more methods inside the implementation (anonymous class), then we can't call them by using instance since the methods not available at the time of object creation.
Calling the methods that are defined inside anonymous inner type will be as shown.
Note:
Anonymous inner type is simply providing implementation to the corresponding abstract class / interface. 
So we are able to create object to abstract class and an interface by providing implementation in the form of anonymous inner type.
You can observe the behavior by practicing this code.

No comments:

Post a Comment