What is an Abstract Class
Abstraction is another core pillar of object-oriented programming (OOP).
It means showing only the essential features of an object and hiding the complex implementation details.
In Java, abstract classes are one way to implement this idea.
An abstract class is a class that cannot be instantiated directly โ it acts as a template for other classes.
It may contain:
Abstract methods: declared without a body โ the child class must provide the implementation.
Concrete methods: normal methods with full code.
Fields: variables that can be inherited by child classes.
Why use an abstract class?
To define a common blueprint for multiple subclasses.
To enforce that certain methods must be implemented by the child class.
To share common code while still keeping some parts flexible.
You declare an abstract class using the abstract
keyword.
Example:
Key points:
Animal
cannot be instantiated directly: new Animal()
โ compiler error!
makeSound()
is abstract โ child classes must override it.
sleep()
is a normal method โ child classes inherit it as-is.
Letโs see how to use an abstract class:
How it works:
Dog
inherits sleep()
as-is.
Dog
must implement makeSound()
.
Animal
defines the blueprint, Dog
fills in the details.
Key benefit:
Abstract classes help you design general contracts with flexible implementations.