Java, as an object-oriented programming language, provides several powerful features, two of which are abstract classes and anonymous classes. In this blog post, we will delve into these concepts and understand how they work together.
Abstract Classes
In Java, an abstract class is a class that cannot be instantiated directly. It often contains one or more abstract methods, which are methods declared without any implementation. These classes represent a concept which is not fully defined and hence, cannot be instantiated directly.
Here’s an example of an abstract class:
abstract class AbstractClass {
abstract void abstractMethod();
}
In the above code, AbstractClass
is an abstract class with an abstract method abstractMethod()
. This class cannot be instantiated directly because it’s not fully defined.
Anonymous Classes
An anonymous class in Java is a class that is defined and instantiated in a single statement without a name. They are often used when you need to create an instance of an object with certain “extras” such as overriding methods from its superclass or implementing methods from an interface.
You can create instance of an anonymous class that extends an abstract class but but not the instance of abstract class:
public class AbstractClassDemo {
public static void main(String[] args) {
AbstractClass abstractClassObject = new AbstractClass() {
@Override
void abstractMethod() {
System.out.println("Implementing the Abstract class Method.");
}
};
abstractClassObject.abstractMethod();
}
}
In the above code, new AbstractClass() {...}
is defining an anonymous class that’s a subclass of AbstractClass
, and it’s providing an implementation for the abstract method abstractMethod()
. Then it’s creating an instance of this anonymous class. The reference to this object is of type AbstractClass
, so it can be used to call any methods defined or inherited by AbstractClass
.
You can not create an object of an abstract class.
https://stackoverflow.com/questions/16785922/creating-the-instance-of-abstract-class-or-anonymous-class
You can create an object of a class that extents your abstract class.
Conclusion
In conclusion, while you cannot create an instance of an abstract class directly in Java, you can create an instance of an anonymous class that extends the abstract class. This anonymous class acts like an inner class that extends the abstract class, and it belongs to your anonymous class. This is a powerful feature of Java that allows for greater flexibility and reusability in your code.