Abstraction allows us to hide the complex implementation details and show only the essential features of an object. Think of it like the steering wheel of a car – you use it to drive, but you don’t need to understand how the engine works.
Why Use Abstraction?
Abstraction helps in:
- Reducing complexity
- Improving code readability and maintainability
- Enforcing standardization using interfaces
- Separating 'what' an object does from 'how' it does it
How to Achieve Abstraction in Java?
Java provides two main tools to achieve abstraction:
- Abstract Classes
- Interfaces
1. Abstract Classes in Java
An abstract class is a class that cannot be instantiated directly. It can have both abstract methods (without a body) and concrete methods (with a body).
Syntax of Abstract Class
abstract class Animal {
abstract void sound(); // abstract method
void sleep() { // concrete method
System.out.println("Sleeping...");
}
}
Extending Abstract Class
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
Main Class to Run
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Outputs "Bark"
d.sleep(); // Outputs "Sleeping..."
}
}
Bark
Sleeping...
2. Interfaces in Java
An interface is a 100% abstract type in Java. It can only contain abstract methods (until Java 7), and from Java 8 onwards, it can also contain default and static methods with implementations.
Declaring and Using an Interface
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starting...");
}
public void stop() {
System.out.println("Car stopping...");
}
}
Main Class to Run
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.start(); // Outputs "Car starting..."
c.stop(); // Outputs "Car stopping..."
}
}
Car starting...
Car stopping...
Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have both abstract and concrete methods | Abstract methods only (until Java 7); default/static from Java 8 |
| Multiple Inheritance | Not supported | Supported |
| Access Modifiers | Can use any access modifier | All methods are public by default |
| Constructor | Can have constructors | Cannot have constructors |
Real-Life Analogy
Imagine a remote control – it represents an interface. Every brand of TV has a different implementation (class), but the functions like power, volume, and channel are standardized. You press a button without knowing the circuit behind it.
Conclusion
By designing classes with abstract methods or interfaces, we enforce a contract that subclasses must fulfill, without worrying about their specific implementation details.
