Abstraction in Java is the process of hiding internal implementation details and showing only essential functionality to the user. It focuses on what an object does rather than how it does it.
Key features of abstraction:
Abstraction hides the complex details and shows only essential features.
Abstract classes may have methods without implementation and must be implemented by subclasses.
By abstracting functionality, changes in the implementation do not affect the code that depends on the abstraction.
How to Achieve Abstraction in Java?
Java provides two ways to implement abstraction, which are listed below:
Abstract Classes (Partial Abstraction)
Interface (100% Abstraction)
Real-Life Example of Abstraction
The television remote control is the best example of abstraction. It simplifies the interaction with a TV by hiding all the complex technology. We don't need to understand how the tv internally works, we just need to press the button to change the channel or adjust the volume.
example :
// Working of Abstraction in Java
abstract class Geeks {
abstract void turnOn();
abstract void turnOff();
}
// Concrete class implementing the abstract methods
class TVRemote extends Geeks {
@override
void turnOn() {
System.out.println("TV is turned ON.");
}
@Override
void turnOff() {
System.out.println("TV is turned OFF.");
}
}
// Main class to demonstrate abstraction
public class Main {
public static void main(String[] args) {
Geeks remote = new TVRemote();
remote.turnOn();
remote.turnOff();
}
}
output :
TV is turned ON.
TV is turned OFF.
Explanation :
Geeks is abstract class defining turnOn() and turnOff() methods.
TVRemote class implements the abstract methods with specific logic.
Main class uses Geeks remote = new TVRemote(); to interact without knowing the internal implementation
Abstract class :
abstract class is a way to achieve abstraction in Java. It is declared using the abstract keyword and can contain both abstract methods non abstract methods. Abstract classes cannot be instantiated directly and are meant to be extended by subclasses. Besides abstraction, abstract classes also allow code reusability through shared behavior and state.
Top comments (0)