Introduction

  • Abstraction can be thought of as the natural extension of 1. Encapsulation.
  • Helps hiding the complexity of the system by exposing only the essential features and behaviors while hiding the unnecessary details, in order to reduce the complexity of the system.
  • Abstraction helps in defining the concept of the object, focusing on what the object does rather than how it does it.
  • It can be achieved through abstract and Interface classes.

Abstraction is like using a TV remote. You press buttons to change channels without needing to know how the TV works inside.

Advantages and Abstraction:

  • Increase security and confidentiality.
  • Simplify on client code.

Examples:

Continuing with the BankAccount example, abstraction would involve defining the concept of a “bank account” by specifying what actions you can perform with it (like deposit, withdraw, and check balance) without worrying about how these actions are implemented internally.

public interface Account {
    void deposit(double amount);
    void withdraw(double amount);
    double getBalance();
}

Here, the Account interface represents an abstract idea of what an account should do. It doesn’t care about the specific implementation details of how these methods work—just that they exist and can be used.

Other Examples:

abstract class Appliance {
    abstract void turnOn();
}
 
class TV extends Appliance {
    void turnOn() {
        System.out.println("TV is now ON.");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Appliance myTV = new TV();
        myTV.turnOn(); // Outputs: TV is now ON.
    }
}
interface Playable {
    void play();
}
 
class VideoGame implements Playable {
    public void play() {
        System.out.println("Playing the video game!");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Playable game = new VideoGame();
        game.play(); // Outputs: Playing the video game!
    }
}