Java Abstraction


What is Abstraction in Java

Abstraction in Java is the process of hiding the complex implementation details and showing only the essential features of an object. It allows the user to focus on what an object does instead of how it does it.

In simpler words, abstraction helps reduce complexity by showing only the necessary information to the outside world. For example, when you use a mobile phone, you just press a button to make a call. You don’t need to know how the phone’s internal circuits work. That’s abstraction in action.

In Java, abstraction can be achieved using abstract classes and interfaces. Both allow developers to define structure without exposing the full implementation.

Why Use Abstraction in Java

Abstraction is useful when you want to simplify your code and improve maintainability. It allows developers to focus on the required functionality without worrying about underlying logic.

It also makes your program more flexible. If you need to change the implementation, you can do so without modifying the parts of the code that use the abstraction.

For example, if you have different types of bank accounts — savings, current, or fixed deposit — you can create a common abstract class BankAccount and implement specific logic in each subclass. This helps maintain a clean, organized structure.

How to Achieve Abstraction in Java

There are two main ways to achieve abstraction in Java:

  1. Using Abstract Classes

    • An abstract class is declared with the keyword abstract.

    • It can have both abstract methods (without implementation) and regular methods (with implementation).

    • Abstract classes cannot be instantiated directly.

  2. Using Interfaces

    • An interface contains only abstract methods (before Java 8) and constants.

    • From Java 8 onwards, interfaces can also have default and static methods.

    • A class can implement multiple interfaces, which helps achieve multiple inheritance.

Example of Abstraction Using Abstract Class

abstract class Animal {
    // Abstract method (no implementation)
    public abstract void makeSound();

    // Regular method
    public void sleep() {
        System.out.println("Sleeping...");
    }
}

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

class Cat extends Animal {
    public void makeSound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.makeSound();
        dog.sleep();

        Animal cat = new Cat();
        cat.makeSound();
        cat.sleep();
    }
}

Explanation:
Here, the class Animal is abstract and defines the abstract method makeSound(). The subclasses Dog and Cat provide their own implementations for this method. The method sleep() is a regular method available to all subclasses. This approach hides unnecessary details and focuses only on what every animal must do — make a sound.

Example of Abstraction Using Interface

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

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

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

public class Main {
    public static void main(String[] args) {
        Vehicle car = new Car();
        car.start();
        car.stop();
    }
}

Explanation:
The interface Vehicle defines two abstract methods — start() and stop(). The class Car implements this interface and provides concrete implementations. The main program interacts only with the Vehicle interface, not the specific implementation. That’s abstraction in practice.

Real-Life Example of Abstraction

Imagine an ATM machine. When you withdraw cash, you only interact with the machine’s screen and buttons. You don’t see how it connects to your bank account, checks your balance, or processes the transaction.

Similarly, in Java, abstraction hides internal details of how something works and exposes only the operations needed by the user.

Abstract Class vs Interface

Feature Abstract Class Interface
Declaration Declared using abstract keyword Declared using interface keyword
Methods Can have both abstract and non-abstract methods Contains abstract methods (and default/static methods from Java 8)
Variables Can have instance and static variables Only public, static, and final variables
Inheritance Supports single inheritance Supports multiple inheritance
Use Case Used when classes share common behavior Used when different classes should follow the same contract

Advantages of Abstraction

  1. Simplifies Complex Systems: Hides unnecessary details, making code easier to understand.

  2. Improves Code Reusability: Common structure can be reused in different implementations.

  3. Enhances Flexibility: You can change internal logic without affecting external code.

  4. Supports Maintenance: Reduces code duplication and dependency.

  5. Promotes Design Consistency: Enforces a clear structure across multiple classes.

Key Points About Abstraction in Java

  • Abstract classes cannot be instantiated directly.

  • Abstract methods have no body and must be implemented by subclasses.

  • Interfaces define a contract that implementing classes must follow.

  • Abstraction focuses on what to do, not how to do it.

  • It improves scalability and structure in large applications.

Summary of the Tutorial

Abstraction in Java helps simplify complex systems by hiding unnecessary details and exposing only essential functionalities. It is implemented through abstract classes and interfaces, which define a common structure for related objects. Abstraction promotes cleaner code, flexibility, and easier maintenance. By using it effectively, developers can build more organized and scalable applications.


Practice Questions

  1. Create an abstract class Shape with an abstract method area() and a regular method display(). Extend it in classes Circle and Rectangle to calculate and display their respective areas.

  2. Write a Java program with an abstract class Vehicle that contains an abstract method startEngine(). Create subclasses Car and Bike that provide their own implementations.

  3. Develop an abstract class Bank with abstract method getRateOfInterest(). Create subclasses SBI, HDFC, and ICICI that return different rates of interest. Display the rate for each bank in the main class.

  4. Define an interface Payment with methods pay() and refund(). Implement it in classes CreditCardPayment and UPIPayment with proper messages for each method.

  5. Create an abstract class Appliance with fields brand and price, and an abstract method turnOn(). Extend it with WashingMachine and Microwave classes that override the turnOn() method.

  6. Write a Java program using an interface Playable with a method play(). Implement it in MusicPlayer and VideoPlayer classes to demonstrate polymorphism through abstraction.

  7. Create an abstract class Employee with abstract method calculateSalary(). Extend it in FullTimeEmployee and PartTimeEmployee classes to compute salary differently.

  8. Design an interface Transport with methods bookTicket() and cancelTicket(). Implement it in classes Bus and Train and show their respective outputs.

  9. Write a Java program with an abstract class Animal containing abstract method sound() and regular method sleep(). Extend it with Dog and Cat classes to demonstrate both abstract and non-abstract methods.

  10. Create an interface Calculator with methods add(), subtract(), multiply(), and divide(). Implement it in a class SimpleCalculator and perform all arithmetic operations.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top