Abstraction in Java
Abstraction in Java is a process of hiding the implementation details and showing only the functionality to the user. It helps to reduce complexity and increase efficiency.
Key Points:
Abstraction = Hiding Internal Details
Only show what an object does, not how it does it.
Achieved using:
1.Abstract Classes
2.Interfaces
1. Abstract Class:
Can have abstract methods (no body) and concrete methods (with body).
Cannot be instantiated.
Used when classes share common behavior.
Example.
abstract class Animal {
abstract void sound(); // abstract method
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Barks");
}
}
2. Interface:
All methods are abstract (by default in older versions of Java).
A class implements an interface to provide behavior.
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starts");
}
}
Real-Life Example:
TV Remote (Abstraction):
You press the power button, it turns on.
You don’t know the internal wiring.
Comments
Post a Comment