Java Abstraction
Java Abstraction
Abstraction in Java is one of the key Object-Oriented Programming (OOP) principles.
It hides internal implementation details and shows only the essential features to the user.
🔹 Why Use Abstraction?
-
To reduce complexity of the program.
-
To provide security by hiding implementation details.
-
To increase reusability and flexibility.
🔹 How is Abstraction Achieved in Java?
Java achieves abstraction in two ways:
| Method | Description |
|---|---|
| Abstract Classes | Can have both abstract (unimplemented) and non-abstract (implemented) methods. |
| Interfaces | All methods are abstract by default (before Java 8), used to achieve full abstraction. |
🧩 1. Abstract Class Example
An abstract class cannot be instantiated (you cannot create objects of it).
It may contain abstract methods (no body) and defined methods (with body).
🔧 Example:
✔ Output:
🧩 2. Interface Example
Interfaces provide 100% abstraction (before Java 8).
A class must implement all methods of an interface.
🔧 Example:
✔ Output:
⚙ Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have abstract + non-abstract methods | Only abstract (before Java 8) |
| Constructors | Allowed | Not allowed |
| Multiple Inheritance | Not supported | Supported |
| Variables | Can be any type | Always public static final (constants) |
🎯 Real-Life Example of Abstraction
You use a TV remote without knowing the internal circuits.
Example:
🏁 Summary
-
Abstraction hides complexity and exposes only necessary functionality.
-
Achieved using abstract classes and interfaces.
-
Helps in clean, secure, and maintainable code.
