Abstraction in Java is a core concept of Object-Oriented Programming (OOP). It means hiding unnecessary implementation details and showing only the essential features of an object.
Abstraction focuses on what an object does instead of how it does it.
Example:
When you drive a car, you use the steering wheel, accelerator, and brakes — you don’t need to know how the engine works internally.
How Abstraction is Achieved in Java
In Java, abstraction is implemented using:
- Abstract Classes
- Declared using the keyword abstract
- Can have:
- Abstract methods (no body)
- Concrete methods (with body)
abstract class Animal {
abstract void sound(); // abstract method
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
2. Interfaces
- Used for 100% abstraction (traditionally)
- All methods are abstract by default (until Java 8 added default methods)
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starts with a key");
}
}
Key Points
- You cannot create objects of abstract classes directly.
- Interfaces support multiple inheritance, while classes do not.
- Abstraction helps in:
- Reducing complexity
- Increasing code reusability
- Improving security (hiding data)
Difference from Encapsulation
- Abstraction → Hides implementation details
- Encapsulation → Hides data (using private variables and getters/setters)
Top comments (0)