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:
- 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");
}
}
📁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);
}
}
📁 User.java
package demo;
public class User extends SBI {
public static void main(String[] args) {
User user = new User();
user.withdraw();
}
}
Output:
ATM class constructor
SBI class constructor
Withdraw successful
Remaining balance = 8000
Top comments (0)