Abstraction in Java
What is Abstraction?
Abstraction is the process of hiding internal implementation details and showing only the essential features to the user.
-
Think of it like using a car:
- You use the steering wheel and accelerator…
- But you don’t need to know how the engine or fuel injection system works!
How is Abstraction Achieved in Java?
Java provides two ways to achieve abstraction:
Tool | Description |
---|---|
Abstract Classes | Partial abstraction (can have both abstract and concrete methods) |
Interfaces | Full abstraction (Java 8+ allows default methods too) |
Abstract Class
An abstract class cannot be instantiated. It may contain abstract methods (no body) and concrete methods (with body).
Syntax:
abstract class Shape {
abstract void draw(); // abstract method
void display() {
System.out.println("Displaying shape...");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing Circle");
}
}
Usage:
public class Main {
public static void main(String[] args) {
Shape s = new Circle(); // Abstract class reference to concrete class
s.draw();
s.display();
}
}
Output:
Drawing Circle
Displaying shape...
Interface
An interface is a contract — any class that implements it must provide definitions for all its methods.
Syntax:
interface Animal {
void makeSound(); // implicitly public and abstract
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks");
}
}
Usage:
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound();
}
}
Output:
Dog barks
Abstract Class vs Interface
Feature | Abstract Class | Interface |
---|---|---|
Methods | Can have both abstract and normal methods | Only abstract methods (Java 8+ allows default/static) |
Variables | Can have instance variables | Only constants (public static final) |
Inheritance | Supports single inheritance | Supports multiple inheritance |
Constructor | Yes | No |
Why Use Abstraction?
- Hide complexity
- Improve modularity
- Enhance code readability
- Encourage loose coupling
Real-World Analogy
-
Using an ATM:
- You press buttons (interface)
- Internally, it accesses your account, verifies PIN, updates the database (implementation)
You don't need to know how all of that works — that’s abstraction!