An abstract
class is a special type of class that cannot be instantiated. It contains one or more abstract
methods, which are methods with unimplemented code. It is used to represent pure concepts without any detail.
Below is an example of an abstract
class.
// Shape is an abstract classabstract class Shape {String name;abstract void draw(); // abstract method}
In the example above, we have an abstract
class, Shape
, where we can have a draw()
method before it is implemented in different subclasses like Rectangle
, Circle
, etc.
Refer to the class diagram below to understand the class hierarchy better.
Abstract classes are used when you want to provide common functionality for all your objects, but you don’t know at the time of writing the program what kind of methods would be needed.
For example, you might want to design a Shape
concept in your program. You will need to implement the draw()
method in subclasses like Rectangle
, Circle
, Triangle
, etc. But there is no way you can know at the time of writing the program what the required details are to implement it.
You might start with not implementing the methods, but it is possible that in the future you will need them. So, instead of writing all these methods in every class where they might be required, we design an abstract
class called Shape
and put the unimplemented methods inside this abstract
class.
See the example below to understand this better. Here, we inherit from the Shape
class and define the draw()
method in the Circle
subclass.
public class Circle extends Shape {@Overridepublic void draw() {System.out.println("Circle");}public static void main(String[] args) {Circle circle = new Circle();circle.draw();}}
abstract
class inheritableAll subclasses can inherit an abstract
class and extend the functionality of their superclass by overriding the unimplemented methods in their class. They will also inherit all non-abstract methods defined in their superclass.
public class Rectangle extends Shape {@Overridepublic void draw() {System.out.println("Rectangle");}public static void main(String[] args) {Rectangle rectangle = new Rectangle();rectangle.draw();}}
In the examples above, we have a class called Shape
with an abstract
method called draw
. We also have classes like Circle
and Rectangle
which extend the Shape
class.
We can overwrite the draw()
method in both the classes. This is where abstract
classes come into picture. All we need to do is define the draw method in the abstract
class, and all sub-classes of Shape
will inherit the draw()
method and, wherever required, overwrite the abstract
method.