What is Abstraction In Java ? | How to achieve abstraction?



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

Post a Comment (0)

Previous Post Next Post