DEV Community

Indumathy
Indumathy

Posted on

Abstraction

Abstraction in Java
Definition:
Abstraction is the process of hiding implementation details and showing only essential functionality to the user.

  • We know what it does, but not how it does it.

Real-Time Example:
When using an ATM machine:
You press Withdraw
You get money
But you don’t know the internal banking process.
That is Abstraction.
How to Achieve Abstraction in Java?

  1. Using Abstract Class
  2. Using Interface (100% abstraction)

** Example Using Abstract Class**

✔ Abstract Class

abstract class Payment {

abstract void pay();   // abstract method

void message() {       // normal method
    System.out.println("Payment processing");
}
Enter fullscreen mode Exit fullscreen mode

}

✔ Child Class

class UPI extends Payment {

void pay() {
    System.out.println("Paid using UPI");
}

public static void main(String[] args) {

    UPI u = new UPI();
    u.message();
    u.pay();
}
Enter fullscreen mode Exit fullscreen mode

}

✔ Output:

Payment processing
Paid using UPI

Why Abstraction?

✔ Reduces complexity
✔ Improves security
✔ Increases maintainability
✔ Focus on "What" not "How"

*Important Points *

Abstract class can contain:

Abstract methods
Normal methods
Instance variables
Constructors

✅ We cannot create object of abstract class directly.
✅ Child class must implement abstract methods.

Top comments (0)