Abstraction in Java

Abstraction is the process of hiding the implementation details of a class or an object and exposing only the essential features. It allows you to focus on the functionality provided by an object rather than how it is implemented. In Java, abstraction is achieved through abstract classes and interfaces.

Abstract Classes

An abstract class is a class that cannot be instantiated and is meant to be extended by other classes. It can contain abstract methods, regular methods, variables, and constructors.

Syntax

To declare an abstract class, use the abstract keyword in the class declaration.


abstract class AbstractClass {
    // abstract methods
    abstract void abstractMethod();

    // regular methods
    void regularMethod() {
        // method implementation
    }
}

Example

Let's consider an example where we have an abstract class called Shape, which defines an abstract method calculateArea() that needs to be implemented by its subclasses.


abstract class Shape {
    abstract double calculateArea();
}

class Rectangle extends Shape {
    double calculateArea() {
        // calculate area for rectangle
    }
}

class Circle extends Shape {
    double calculateArea() {
        // calculate area for circle
    }
}

public class Main {
    public static void main(String[] args) {
        Shape rectangle = new Rectangle();
        Shape circle = new Circle();

        double rectangleArea = rectangle.calculateArea();
        double circleArea = circle.calculateArea();

        System.out.println("Rectangle area: " + rectangleArea);
        System.out.println("Circle area: " + circleArea);
    }
}

Note

Abstraction is a powerful concept in Java that allows you to create high-level models of complex systems. Abstract classes and interfaces provide mechanisms to achieve abstraction and define contracts between classes. By using these concepts effectively, you can create flexible and maintainable code.