DEV Community

Bala Murugan
Bala Murugan

Posted on

Abstraction In Java

What is Abstraction:

Abstraction is an OOP concept that hides implementation details and shows only the essential features of an object.

Why Use Abstraction:

  • Reduces code complexity.
  • Improves security by hiding internal details.
  • Makes code easier to maintain and reuse.

When to Use Abstraction

Use abstraction when you want to define what an object should do without specifying how it does it. It is useful when multiple classes share common behavior but have different implementations.

Example:

Consider a car. A driver uses the steering wheel, brake, and accelerator without knowing how the engine works internally. The driver only sees the necessary features, while the internal implementation is hidden. This is abstraction.

code:

abstract class Animal {
    abstract void sound();   // Abstract method
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
    }
}

Enter fullscreen mode Exit fullscreen mode
Output:

Dog barks

Enter fullscreen mode Exit fullscreen mode

Explanation :

  • Animal is an abstract class.

  • sound() is an abstract method (no implementation).

  • Dog provides the implementation of sound().

  • We know that an animal makes a sound, but the exact sound depends on the animal.

    This hides the implementation details and shows only the required behavior, which is called abstraction.

Top comments (0)