How we can Achieve Abstraction in Java
In Java, abstraction is achieved through the use of abstract classes and interfaces. Both abstract classes and interfaces allow you to declare abstract methods, which are methods without a body. Concrete classes that extend an abstract class or implement an interface must provide implementations for these abstract methods.
There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)
Let’s go through examples of both abstract classes and interfaces to demonstrate how abstraction is achieved in Java:
Abstraction using Abstract Class:
// Abstract class representing a shape
abstract class Shape {
// Abstract method to calculate area
public abstract double calculateArea();
}
// Concrete class Circle extending the abstract class
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// Implementation of the abstract method for Circle
@Override
public double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
}
// Concrete class Rectangle extending the abstract class
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementation of the abstract method for Rectangle
@Override
public double calculateArea() {
return length * width;
}
}
In this example, the Shape
class is an abstract class that declares an abstract method calculateArea()
. The Circle
and Rectangle
classes are concrete classes that extend the Shape
abstract class and provide specific implementations for the calculateArea()
method.
Abstraction using Interface:
// Interface representing a printable item
interface Printable {
void print();
}
// Concrete class implementing the interface
class Document implements Printable {
private String content;
public Document(String content) {
this.content = content;
}
// Implementation of the interface method
@Override
public void print() {
System.out.println(content);
}
}
In this example, the Printable
interface declares a single abstract method print()
. The Document
class implements the Printable
interface, providing a specific implementation for the print()
method.
This demonstrates how abstraction allows you to create a common interface for a set of related classes, promoting code reuse and providing a clear separation between interface and implementation.