1.2.7 Abstract Classes
Abstract classes are a key concept in Java that allow you to define a common interface and partial implementation for a group of related classes. They are used to create a base class that cannot be instantiated on its own but must be extended by other classes.
Key Concepts
1. Abstract Class Definition
An abstract class is defined using the abstract
keyword. It can contain both abstract and non-abstract methods. Abstract methods are declared without an implementation, while non-abstract methods provide a default implementation.
2. Abstract Methods
Abstract methods are methods declared in an abstract class without a body. They must be implemented by any concrete subclass. Abstract methods are defined using the abstract
keyword and end with a semicolon instead of a method body.
3. Concrete Subclasses
Concrete subclasses are classes that extend an abstract class and provide implementations for all its abstract methods. They can be instantiated and used as regular classes.
4. Inheritance and Polymorphism
Abstract classes support inheritance and polymorphism. A subclass can override methods from the abstract class, allowing for different behaviors while maintaining a common interface.
Examples and Analogies
Consider an abstract class named Shape
:
abstract class Shape { abstract double area(); void displayArea() { System.out.println("Area: " + area()); } } class Circle extends Shape { double radius; Circle(double radius) { this.radius = radius; } @Override double area() { return Math.PI * radius * radius; } } class Square extends Shape { double side; Square(double side) { this.side = side; } @Override double area() { return side * side; } } public class Main { public static void main(String[] args) { Shape circle = new Circle(5); Shape square = new Square(4); circle.displayArea(); // Output: Area: 78.53981633974483 square.displayArea(); // Output: Area: 16.0 } }
In this example, Shape
is an abstract class with an abstract method area()
and a non-abstract method displayArea()
. The Circle
and Square
classes extend Shape
and provide their own implementations for the area()
method.
Think of an abstract class as a blueprint for a house. The blueprint specifies the layout and some basic features (like the foundation and walls), but it doesn't provide the complete details (like the color of the walls or the type of flooring). The actual houses built from this blueprint can have different colors and flooring, but they all share the same basic structure.
By using abstract classes, you can create a common interface and default behavior for a group of related classes, promoting code reuse and maintainability.