Introduction to Abstraction In Java:
Abstraction is the process of hiding the implementation details of a class and only exposing the necessary information to the outside world. This allows for the creation of simplified, higher-level interfaces that are easier to use and understand.
There are two ways to achieve abstraction in Java:Â
1. Abstract classesÂ
2. Interfaces.
An Abstract class is a class that cannot be instantiated but can be inherited by other classes.Â
An abstract class can contain both abstract and concrete methods (methods with and without a body, respectively).Â
For example:
abstract class Shape {
Â
abstract double getArea();
Â
public void displayArea() {
Â
System.out.println("Area = " + getArea());
Â
}
Â
}
Â
class Circle extends Shape {
Â
double radius;
Â
Circle(double r) {
Â
radius = r;
Â
}
Â
@Override
Â
double getArea() {
Â
return Math.PI * radius * radius;
Â
}
Â
}
In this example, the "Shape" class is an abstract class that contains an abstract method "getArea()" as well as a concrete method "displayArea()". The "Circle" class extends "Shape" and provides an implementation for the "getArea()" method.
An interface is a collection of abstract methods that must be implemented by any class that implements the interface.Â
For example:
interface Shape {
Â
double getArea();
Â
double getPerimeter();
Â
}
Â
class Rectangle implements Shape {
Â
double width;
Â
double height;
Â
Rectangle(double w, double h) {
Â
width = w;
Â
height = h;
Â
}
Â
@Override
Â
public double getArea() {
Â
return width * height;
Â
}
Â
@Override
Â
public double getPerimeter() {
Â
return 2 * (width + height);
Â
}
Â
}
In this example, the "Shape" interface defines two abstract methods "getArea()" and "getPerimeter()". The "Rectangle" class implements the "Shape" interface and provides an implementation for both methods.
Abstraction allows you to create flexible and reusable code by hiding the implementation details of a class and providing a simplified interface that can be easily used by other parts of the code.Â
It also allows for a clear separation of concerns, making it easier to understand the purpose and function of different parts of the code.
Post a Comment