The following code shows an Example of Abstract Method in Java.

Problem Statement

Create a class Figure and its 2 subclasses Rectangle and Triangle and calculate its area using dynamic method dispatch.

Further, Implement the above program using abstract classes by making the Figure class abstract.

Solution

// Abstract Figure class
abstract class Figure {
    // Abstract method for calculating area (to be implemented by subclasses)
    abstract double calculateArea();
}

// Rectangle subclass
class Rectangle extends Figure {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // Implement the abstract method to calculate the area of a rectangle
    @Override
    double calculateArea() {
        return length * width;
    }
}

// Triangle subclass
class Triangle extends Figure {
    private double base;
    private double height;

    public Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    // Implement the abstract method to calculate the area of a triangle
    @Override
    double calculateArea() {
        return 0.5 * base * height;
    }
}

public class AreaCalculator {
    public static void main(String[] args) {
        // Create objects of Rectangle and Triangle
        Figure rectangle = new Rectangle(5.0, 3.0);
        Figure triangle = new Triangle(4.0, 6.0);

        // Calculate and display the area using dynamic method dispatch
        System.out.println("Area of the Rectangle: " + rectangle.calculateArea());
        System.out.println("Area of the Triangle: " + triangle.calculateArea());
    }
}

In this program:

  1. We have an abstract class Figure with an abstract method calculateArea(). This method will be implemented by the subclasses.
  2. The Rectangle and Triangle classes are subclasses of Figure. They implement the calculateArea() method to calculate the area specific to each shape.
  3. In the main method, we create objects of the Rectangle and Triangle classes and store them in references of the Figure type. This allows us to use dynamic method dispatch to call the appropriate calculateArea() method based on the actual object type.
  4. We calculate and display the areas of the rectangle and triangle using dynamic method dispatch.

Using abstract classes and method overriding, this program demonstrates the concept of polymorphism and dynamic method dispatch to calculate the areas of different shapes.


Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites