DEV Community

Kavitha
Kavitha

Posted on

Abstraction in Java

Introduction

  • Abstraction is one of the four core principles of Object-Oriented Programming (OOPS) in Java.
  • It focuses on hiding implementation details and showing only essential features to the user.

In simple words:
Abstraction shows what an object does, not how it does it.

What is Abstraction?
=>Abstraction means hiding internal details and providing only required functionality.

Example from real life:

  • When you drive a car, you know how to use the steering, brake, and accelerator
  • You do not need to know how the engine works internally

How Abstraction is Achieved in Java
Java achieves abstraction in two ways:

  1. Abstract Class 2.Interface

What is an Abstract Class?

  • A class declared using the keyword abstract
  • Object cannot be created for an abstract class Example: Abstract Class

📁 ATM.java (Abstract Parent)

package demo;

public abstract class ATM {

    int balance = 10000;

    // abstract method
    public abstract void withdraw();

    // constructor
    ATM() {
        System.out.println("ATM class constructor");
    }
}
Enter fullscreen mode Exit fullscreen mode

📁SBI.java

package demo;

public class SBI extends ATM {

    SBI() {
        System.out.println("SBI class constructor");
    }

    @Override
    public void withdraw() {
        int amount = 2000;
        balance = balance - amount;
        System.out.println("Withdraw successful");
        System.out.println("Remaining balance = " + balance);
    }
}
Enter fullscreen mode Exit fullscreen mode

📁 User.java

package demo;

public class User extends SBI {

    public static void main(String[] args) {
        User user = new User();
        user.withdraw();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

ATM class constructor
SBI class constructor
Withdraw successful
Remaining balance = 8000
Enter fullscreen mode Exit fullscreen mode

Top comments (0)