What is Abstraction in Java?
Abstraction is one of the four pillars of Object-Oriented Programming (OOP). It is the process of hiding internal implementation details and showing only the essential features of an object.
In Java, abstraction is achieved using:
- Abstract classes
- Interfaces
Why Use Abstraction?
- To reduce complexity by hiding unnecessary details.
- To provide a blueprint for subclasses.
- To promote loose coupling in code.
Abstract Class Example
What is an Abstract Class?
- A class declared using the
abstract keyword.
- Can have abstract methods (without body) and concrete methods (with body).
- Cannot be instantiated directly.
// Abstract Class
abstract class Animal {
// Abstract method (no body)
abstract void sound();
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
// Subclass
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class TestAbstraction {
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
a.sound(); // Dog barks
a.sleep(); // Sleeping...
}
}
Output:
Dog barks
Sleeping...
Interface Example
What is an Interface?
- A pure abstraction.
- All methods are implicitly abstract and public (Java 7 and below).
- Supports multiple inheritance.
// Interface
interface Vehicle {
void start();
void stop();
}
// Implementation
class Car implements Vehicle {
public void start() {
System.out.println("Car started");
}
public void stop() {
System.out.println("Car stopped");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Vehicle v = new Car();
v.start(); // Car started
v.stop(); // Car stopped
}
}
Output:
Car started
Car stopped
Abstract Class vs Interface
| Feature |
Abstract Class |
Interface |
| Method Types |
Abstract + Concrete |
Abstract (default, static from Java 8) |
| Multiple Inheritance |
Not supported |
Supported |
| Constructors |
Yes |
No |
| Access Modifiers |
Can have any |
Only public (for methods) |