Subclass Method Accepts Variable Number of Arguments in Abstract Class In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method from an abstract class and changes the parameter list to accept a variable number of arguments

The code defines an abstract class MathOperation with an abstract method calculate, and a concrete subclass Calculator that extends MathOperation and provides an implementation for the calculate method. The calculate method in the Calculator class takes a variable number of integer arguments and calculates their sum.

  • MathOperation is an abstract class with an abstract method calculate that takes an array of integers (int... numbers) as its parameter.
  • Calculator is a subclass of MathOperation. It overrides the calculate method and provides an implementation that calculates the sum of the integers passed as arguments.
  • In the Main class, you create an instance of the Calculator class named calculator.
  • You call the calculate method on the calculator object and pass a variable number of integer arguments (10, 20, 30, 40, 50).
  • The calculate method in the Calculator class iterates through the provided integers and calculates their sum.
  • The result is printed to the console using System.out.println.

Source Code

abstract class MathOperation
{
    abstract int calculate(int... numbers);
}
 
class Calculator extends MathOperation
{
    @Override
    int calculate(int... numbers)
	{
        int sum = 0;
        for (int num : numbers)
		{
            sum += num;
        }
        return sum;
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Calculator calculator = new Calculator();
        System.out.println("Sum : " + calculator.calculate(10, 20, 30, 40, 50));
    }
}

Output

Sum : 150