In Java, abstraction is the process of hiding the implementation details of a class or method and exposing only the essential features to the outside world.
It lets you focus on what an object does rather than how it does it.
Why Abstraction?
- Reduces complexity by hiding unnecessary details.
- Increases flexibility — implementation can change without affecting other code.
- Supports loose coupling between components.
Ways to Achieve Abstraction in Java
Java provides two main mechanisms:
1. Abstract Classes
- Declared using the
abstract
keyword. - Can have both abstract methods (no body) and concrete methods (with body).
- Cannot be instantiated directly — only subclasses can.
- Supports constructors and member variables.
Example:
abstract class Vehicle {
abstract void start(); // abstract method
void stop() { // concrete method
System.out.println("Vehicle stopped.");
}
}
class Car extends Vehicle {
void start() {
System.out.println("Car started with a key.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start();
myCar.stop();
}
}
2. Interfaces
- Declared using the
interface
keyword. - All methods are abstract by default (until Java 8, when default and static methods were added).
- A class can implement multiple interfaces (supports multiple inheritance).
- Good for defining contracts.
Example:
interface Animal {
void makeSound(); // implicitly public and abstract
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound();
}
}
Key Differences: Abstract Class vs Interface
Feature | Abstract Class | Interface |
---|---|---|
Methods | Can be abstract or concrete | Abstract (default), can have default & static |
Fields | Can have instance variables | Only public static final constants |
Inheritance | Single inheritance | Multiple inheritance |
Constructor | Can have a constructor | Cannot have constructors |
✅ Quick Analogy:
Think of a TV remote — you only know the buttons (public methods), not the internal circuits (implementation).
That’s abstraction in action.