🧊 Abstraction in Java

Abstraction is an Object-Oriented Programming (OOP) principle in Java that focuses on hiding internal details and showing only the essential features of an object.

✅ Think of it as: “What an object does” instead of “How it does it”


🧠 Real-life Analogy

🚗 When you drive a car:

  • You use the steering wheel, brakes, and accelerator
  • You don’t need to know how the engine works internally

That’s abstraction in action — exposing only what's necessary.


🎯 Key Benefits of Abstraction

Benefit Description
💡 Simplicity Reduce complexity for the user
🔐 Security Hide sensitive code implementation details
♻️ Reusability Abstract code can be reused in multiple contexts
🔄 Maintainability Changes can be made in one place (abstract layer)

💼 How to Achieve Abstraction in Java?

Java provides two ways:

Approach Description
Abstract Class Can have abstract and concrete methods
Interface All methods are abstract (until Java 8+)


📦 Abstract Class Example

abstract class Animal {
    abstract void makeSound(); // abstract method

    void sleep() {
        System.out.println("Sleeping...");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Bark");
    }
}

Usage:

Animal a = new Dog();
a.makeSound(); // Output: Bark
a.sleep();     // Output: Sleeping...

🧩 Interface Example

interface Vehicle {
    void start();
    void stop();
}

class Car implements Vehicle {
    public void start() {
        System.out.println("Car starting...");
    }

    public void stop() {
        System.out.println("Car stopping...");
    }
}

 


📌 Abstract Class vs Interface

Feature Abstract Class Interface
Methods Abstract + Concrete Abstract (default/static allowed since Java 8)
Constructors ✅ Yes ❌ No
Multiple inheritance ❌ Not supported directly ✅ Supported
Access Modifiers Any Public (for methods by default)


✅ Summary

Term Meaning
Abstraction Hiding implementation details
abstract Keyword to define abstract class/method
Interface A pure abstract form of class
Main Goal Simplify usage and improve flexibility
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.