On Day 25, we explore Abstraction, one of the key OOP principles. Abstraction allows us to hide implementation details and expose only the essential features of an object. In Java, we achieve abstraction using abstract classes and abstract methods.
1. What is an Abstract Class?
An abstract class
cannot be instantiated directly. It can contain both normal methods (with a body) and abstract methods (without a body). Subclasses must implement all abstract methods.
abstract class Shape {
// abstract method (no body)
abstract void draw();
// regular method
void info() {
System.out.println("This is a shape.");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a square");
}
}
public class Main {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();
s1.draw();
s2.draw();
s1.info(); // normal method from abstract class
}
}
Explanation: The abstract class Shape
defines an abstract method draw()
that subclasses Circle
and Square
must implement. This ensures that all shapes provide their own implementation of draw()
.
2. Why Use Abstraction?
- Provides a blueprint for subclasses.
- Encourages code reusability and cleaner design.
- Hides complex implementation details from the user.
3. Key Rules
- An abstract class cannot be instantiated directly.
- A subclass must implement all abstract methods unless it is also abstract.
- Abstract classes can have constructors, fields, and regular methods.
Summary
Abstraction in Java focuses on "what to do" rather than "how to do it". Abstract classes and methods act as templates, forcing subclasses to provide specific behavior.