Can We Instantiate an Abstract Class in Java?
Abstract class, we have heard that abstract class are classes which can have abstract methods and it can’t be instantiated. We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.
Example 1
Java
public abstract class ClassOne {
public void printSomething()
{
System.out.println( "Hello in abstract class" );
}
}
class CreateClassOne {
public static void main(String[] args)
{
ClassOne obj = new ClassOne();
}
}
|
Output
prog.java:17: error: ClassOne is abstract; cannot be instantiated
ClassOne obj = new ClassOne();
^
1 error
Example 2
Java
public abstract class ClassOne {
public void printSomething()
{
System.out.println( "Hello in abstract class" );
}
}
class InheritClassOne {
public static void main(String[] args)
{
ClassOne obj = new ClassOne() {};
obj.printSomething();
}
}
|
Output
Hello in abstract class
Is abstract class instantiated here! But that’s not possible!
Yes, the answer is still the same, the abstract class can’t be instantiated, here in the second example object of ClassOne is not created but the instance of an Anonymous Subclass of the abstract class. And then you are invoking the method printSomething() on the abstract class reference pointing to subclass object obj. When you have added { } while creating the object in second class, the compiler takes it as an anonymous class where { } denotes the body of the anonymous class.
Example 1
Java
interface NewClass {
public void show();
}
class AnonymousClassExample {
public static void main(String[] args)
{
NewClass nc = new NewClass() {
public void show()
{
System.out.println(
"This is an anonymous class implementing interface" );
}
};
nc.show();
}
}
|
Output
This is an anonymous class implementing interface
In this example, the interface is not instantiated but an anonymous class is implementing the interface New Class. Now, you may have understood that how the second example worked where instead of abstract class instantiation, an anonymous subclass was created or abstract class were implemented by an abstract class.
Example 2
Java
public abstract class ClassOne {
public ClassOne()
{
System.out.println(
"Anonymous(Unnamed) Subclass object Created" );
}
public void printSomething()
{
System.out.println(
"Hello,in abstract class:printSomething method" );
}
public abstract void implementMethod();
}
class AnonymousClassExample {
public static void main(String[] args)
{
ClassOne obj = new ClassOne() {
@Override public void implementMethod()
{
System.out.println(
"Implemented abstract method in anonymous class" );
}
};
obj.printSomething();
obj.implementMethod();
}
}
|
Output
Anonymous(Unnamed) Subclass object Created
Hello,in abstract class:printSomething method
Implemented abstract method in anonymous class
Last Updated :
07 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...