DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 2 - Abstraction: Hiding Implementation, Exposing Services

After understanding Data Hiding, it's time to learn the second fundamental Object-Oriented Programming (OOP) concept—Abstraction.

In Data Hiding, we protected an object's internal data from direct access.

Abstraction takes this idea one step further.

Instead of hiding only the data, it hides how the system works internally and exposes only the services that users need.

Think about an ATM machine. You can withdraw money, deposit cash, check your balance, or change your PIN with just a few taps. But do you know how the bank validates your PIN, communicates with servers, updates the ledger, or performs fraud detection?

No—and you don't need to.

This is the essence of Abstraction.

What is Abstraction?

Abstraction is the process of hiding the internal implementation details and exposing only the required services to the outside world.

In simple words:

Hide the internal implementation and just highlight the set of services.

The user should focus on what the system does, not how the system does it.

Why Do We Need Abstraction?

Imagine you're driving a car.

You use:

  • Steering wheel
  • Accelerator
  • Brake pedal
  • Gear lever

You don't need to understand:

  • How the engine burns fuel
  • How the transmission works
  • How ABS prevents wheel lock
  • How the ECU controls ignition timing

The car exposes only the controls you need while hiding all the engineering complexity.

Software works in exactly the same way.

Abstraction lets developers expose only the required functionality while keeping implementation details private.

Without Abstraction With Abstraction
Users see implementation details Users see only services
Difficult to use Simple and user-friendly
Hard to maintain Easy to maintain
Tight coupling Loose coupling
Difficult to upgrade Easy to enhance

Real-World Analogy: ATM Machine

An ATM is one of the best examples of Abstraction.

What the Customer Sees

  • Withdraw Cash
  • Deposit Cash
  • Balance Enquiry
  • Mini Statement
  • Change PIN

What the Customer Doesn't See

  • Database queries
  • Account validation
  • Fraud detection
  • Ledger updates
  • Encryption
  • Cash dispenser control
  • Transaction logging
+--------------------------------------+
|          ATM SCREEN                  |
|--------------------------------------|
| Withdraw                             |
| Deposit                              |
| Balance Enquiry                      |
| Mini Statement                       |
| PIN Change                           |
+--------------------------------------+

            ▲
            │
      Visible Services

-----------------------------------------

Database Access
Authentication
Encryption
Fraud Detection
Transaction Logging
Cash Dispenser Logic

        Hidden Implementation
Enter fullscreen mode Exit fullscreen mode

The ATM screen represents the abstraction.

The backend implementation remains completely hidden.

How Does Java Implement Abstraction?

Java provides two mechanisms to implement Abstraction:

  1. Abstract Classes
  2. Interfaces
Feature Abstract Class Interface
Can have abstract methods
Can have implemented methods ✅ (default/static methods)
Constructors
Instance variables Constants only
Multiple inheritance
Primary purpose Partial abstraction Complete contract (service definition)

In enterprise applications, interfaces are commonly used to define services, while abstract classes are used to share common behavior among related classes.

Syntax

Using an Interface

interface ATMService {

    void withdraw(double amount);

    void deposit(double amount);

    double checkBalance();

}
Enter fullscreen mode Exit fullscreen mode

Using an Abstract Class

abstract class Payment {

    abstract void pay(double amount);

}
Enter fullscreen mode Exit fullscreen mode

Basic Example

Let's define an ATM service using an interface.

interface ATMService {

    void withdraw(double amount);

    void deposit(double amount);

    double checkBalance();

}
Enter fullscreen mode Exit fullscreen mode

Now let's implement it.

class SBIATM implements ATMService {

    private double balance = 5000;

    @Override
    public void withdraw(double amount) {

        balance -= amount;

        System.out.println("Withdrawn: " + amount);

    }

    @Override
    public void deposit(double amount) {

        balance += amount;

        System.out.println("Deposited: " + amount);

    }

    @Override
    public double checkBalance() {

        return balance;

    }

}
Enter fullscreen mode Exit fullscreen mode

Using the service:

public class ATMDemo {

    public static void main(String[] args) {

        ATMService atm = new SBIATM();

        atm.deposit(1000);

        atm.withdraw(500);

        System.out.println(atm.checkBalance());

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Deposited: 1000.0
Withdrawn: 500.0
5500.0
Enter fullscreen mode Exit fullscreen mode

How It Works

Step 1

The interface defines what services are available.

Step 2

SBIATM provides the actual implementation.

Step 3

The user interacts only with the ATMService interface.

Step 4

The implementation remains hidden from the user.

This is Abstraction in action.

Rules

Rule 1: Expose Services, Not Implementation

The interface defines only what operations are available.

interface PaymentService {

    void pay(double amount);

}
Enter fullscreen mode Exit fullscreen mode

The implementation is hidden.

Step-by-Step Explanation

Step 1

The interface declares a service.

Step 2

No implementation is provided.

Step 3

Implementing classes provide the logic.

Step 4

Clients use the service without knowing its implementation.


Rule 2: Interfaces Define a Contract

A contract specifies what a class must implement.

interface NotificationService {

    void send(String message);

}
Enter fullscreen mode Exit fullscreen mode

Any implementing class must provide the send() method.

Step-by-Step Explanation

Step 1

The interface defines the required method.

Step 2

Classes agree to implement that method.

Step 3

Different classes can provide different implementations.

Step 4

The caller remains unaware of the implementation details.


Rule 3: Implementations Can Change Without Affecting Clients

class SBIATM implements ATMService {

    @Override
    public void withdraw(double amount) {

        // Validate customer
        // Check database
        // Fraud detection
        // Update ledger
        // Dispense cash

    }

    @Override
    public void deposit(double amount) {
        // Hidden implementation
    }

    @Override
    public double checkBalance() {
        return 0;
    }

}
Enter fullscreen mode Exit fullscreen mode

Tomorrow, the bank may:

  • migrate from Oracle to PostgreSQL
  • introduce AI-based fraud detection
  • improve transaction logging

The interface doesn't change, so the client code continues to work without modification.

Practical Examples

Beginner Example

interface Printer {

    void print();

}
Enter fullscreen mode Exit fullscreen mode

Business Example

interface PaymentService {

    void processPayment(double amount);

}
Enter fullscreen mode Exit fullscreen mode

Implementations:

  • Credit Card
  • UPI
  • Net Banking
  • Wallet

The client simply calls processPayment().


Interview Example

interface NotificationService {

    void sendNotification(String message);

}
Enter fullscreen mode Exit fullscreen mode

Possible implementations:

  • EmailNotification
  • SMSNotification
  • PushNotification
  • WhatsAppNotification

The client doesn't care how the notification is sent.

Visual Explanation

                Client

                  │

                  ▼

          ATMService Interface

      withdraw()

      deposit()

      checkBalance()

                  │

                  ▼

           SBIATM Class

      Database Access

      Validation

      Fraud Detection

      Ledger Update

      Cash Dispenser

      Logging
Enter fullscreen mode Exit fullscreen mode

The client communicates with the interface, not the implementation.

Data Hiding vs Abstraction

This is one of the most frequently asked Java interview questions.

Feature Data Hiding Abstraction
What is hidden? Internal data Internal implementation
Goal Protect data Hide complexity
Implemented using private modifier Abstract classes and interfaces
Primary benefit Security Simplicity, flexibility, maintainability
User sees Controlled data access Available services

Quick Way to Remember

  • Data Hiding = Hide Data
  • Abstraction = Hide Implementation

Common Beginner Mistakes

Mistake 1: Thinking Abstraction Means "No Code"

❌ Incorrect understanding

Many beginners believe abstraction means not writing implementation.

Reality:

Interfaces and abstract classes define contracts. Concrete classes provide the implementation.


Mistake 2: Accessing the Implementation Directly

Instead of writing:

ATMService atm = new SBIATM();
Enter fullscreen mode Exit fullscreen mode

Beginners often write:

SBIATM atm = new SBIATM();
Enter fullscreen mode Exit fullscreen mode

Although this works, programming to the interface provides greater flexibility and follows the Dependency Inversion Principle.


Mistake 3: Confusing Data Hiding with Abstraction

Incorrect Understanding Correct Understanding
Both are the same They solve different problems

Interview Questions

1. What is Abstraction?

Why interviewers ask this

To assess your understanding of one of the core OOP principles.

Expected answer

Abstraction is the process of hiding implementation details and exposing only the essential services to the user.

Common trap

Saying that abstraction hides data. That's Data Hiding.


2. How is Abstraction implemented in Java?

Expected answer

Using abstract classes and interfaces.


3. What is the biggest advantage of Abstraction?

Expected answer

It allows internal implementation to change without affecting the client code, improving flexibility and maintainability.


4. Give a real-world example of Abstraction.

Expected answer

ATM machine, car dashboard, television remote, mobile phone, or online payment gateway.


5. Why do enterprise applications prefer interfaces?

Expected answer

Interfaces reduce coupling, improve flexibility, simplify testing, and allow multiple implementations without changing client code.

Best Practices

  • Program to interfaces rather than concrete classes.
  • Keep interfaces focused on related responsibilities.
  • Hide implementation details from clients.
  • Use meaningful service names such as PaymentService, OrderService, and NotificationService.
  • Keep implementation classes replaceable.
  • Follow the Interface Segregation Principle by avoiding large, unrelated interfaces.

Performance Notes

Abstraction itself introduces minimal overhead. Modern JVMs perform aggressive optimizations such as method inlining, making interface-based designs highly efficient in most applications. The primary benefits of abstraction are flexibility, maintainability, modularity, and testability rather than performance.

Quick Memory Trick 🧠

Think of a TV Remote.

TV Remote

↓

Buttons (Services)

↓

Hidden Electronics

↓

TV Hardware
Enter fullscreen mode Exit fullscreen mode

You press Power, Volume, or Channel.

You don't need to know how infrared signals are encoded or how the television processes them.

Similarly:

  • Interface = Remote buttons
  • Implementation = TV electronics
  • User = Person holding the remote

FAQ

Is Abstraction the same as Encapsulation?

No. Abstraction focuses on hiding implementation details, while Encapsulation bundles data and methods together and often uses Data Hiding to protect the data.

Can an interface contain implemented methods?

Yes. Since Java 8, interfaces can have default and static methods. Since Java 9, they can also have private helper methods.

Which is better: an abstract class or an interface?

Use an interface to define a contract for unrelated classes. Use an abstract class when related classes share common state or behavior.

Can a class implement multiple interfaces?

Yes. Java supports multiple interface inheritance, allowing a class to implement multiple interfaces.

Why is abstraction important in enterprise applications?

It enables teams to modify implementations, replace technologies, improve testing, and add new features without impacting client code.

Key Takeaways

  • Abstraction hides implementation details while exposing only the required services.
  • Java implements abstraction using abstract classes and interfaces.
  • Interfaces define contracts; implementing classes provide the logic.
  • Users interact with services, not implementation details.
  • Abstraction improves security, flexibility, maintainability, modularity, and ease of use.
  • Internal implementations can change without affecting client code.
  • Data Hiding hides data, whereas Abstraction hides implementation.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)