Can we create object of Abstract class in Java

This is a very confusing point for many of freshers in Java Programming. Java doesn’t allow to create Object of Abstract Class directly. You can see what is Abstract Class in Java.


Yes, We can create the Object of Abstract Class in Java but not directly. We can create the Object of Abstract Class indirectly with the help of anonymous inner type.


If you declare the Abstract Class and try to create the Object of Abstract Class then Compiler doesn’t allow to do the same and you will get the Compilation error in your project.


How to create Object of Abstract Class

We can create the object of abstract class indirectly by using anonymous inner type. You can see this in below-mentioned example code –

First Create the Abstract Class –

We have created our Abstract Class “SampleAbs”, Now we will see how can we create the Object of this Abstract Class using anonymous Inner type and class the “displayMessage() method”


You can see within the “Apps” class, We are creating the Object of Abstract Class “sampleAb” and calling the method “displayMessage()” using the Abstract class object. Yes, you can do this and execute the above code on your local machine.


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.

Output –

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The method getMessage() is undefined for the type SampleAbs

No, you can’t call getMessage() method like this because “getMessage()” method is defined inside anonymous inner type and it’s not available to “SampleAbs” , So we can’t call it directly like this.


So, How can we call the methods present inside the anonymous inner type ?  We can call these methods by creating anonymous object i.e Object without reference. See below, How can you call these methods –

Output –

I am method from, Anonymous Inner Type


So this is the way, How can you create the Object of Abstract Class in Java.

0 Comment

Leave a Reply