🔹 Abstraction in Object-Oriented Programming (OOP)
**Abstraction** is one of the four main principles of OOP. It allows us to **hide complex implementation details** and expose only the necessary functionalities to the user. This makes the code **cleaner, more secure, and easier to maintain**.
📌 Why Use Abstraction?
Abstraction helps in **reducing complexity** and **improving code efficiency** by focusing only on what is essential.
- ✅ **Hides Implementation Details** – Users interact with a simplified interface.
- ✅ **Improves Code Readability & Maintainability** – Only relevant details are exposed.
- ✅ **Enhances Security** – Prevents direct access to sensitive data.
- ✅ **Promotes Reusability** – Common functionalities are implemented once.
💡 Real-Life Example
When you use an **ATM machine**, you only interact with the screen and buttons, without knowing the complex internal process of money transactions. **The internal workings are hidden (abstracted) from the user.**
🖥️ Abstraction in Java (Using Abstract Classes)
Abstract classes provide a template for other classes. They **cannot be instantiated directly** and must be inherited.
abstract class Vehicle {
abstract void start(); // Abstract method (No implementation)
void stop() {
System.out.println("Vehicle Stopped");
}
}
class Car extends Vehicle {
void start() {
System.out.println("Car Started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start(); // Output: Car Started
myCar.stop(); // Output: Vehicle Stopped
}
}
🖥️ Abstraction in Java (Using Interfaces)
Interfaces provide **full abstraction** because all methods are **abstract by default**.
interface Animal {
void makeSound(); // No implementation
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark!");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark!
}
}
🎯 Summary
Abstraction helps to **hide unnecessary details** and expose only the required functionalities. It is implemented using **abstract classes** and **interfaces** in Java.