Subclass Method Overrides Interface Method with Different Parameters In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method from an interface and implements a method with the same name but different parameters

Interface MathOperations with a method calculate, and a class Calculator that implements this interface. The Calculator class provides two implementations of the calculate method using method overloading. Here's an explanation of the code:

  • MathOperations is an interface with a method calculate that takes two int parameters and returns an int.
  • Calculator is a class that implements the MathOperations interface. It provides an implementation of the calculate method that takes two int parameters and returns their sum.
  • The Calculator class also overloads the calculate method by providing another version of the method that takes three int parameters and returns their sum.
  • In the Main class, you create an instance of the Calculator class named calculator.
  • You call the two overloaded calculate methods on the calculator object. The first call calculator.calculate(4, 7) invokes the two-argument version of the method, and the second call calculator.calculate(10, 20, 30) invokes the three-argument version.

Source Code

interface MathOperations
{
    int calculate(int a, int b);
}
 
class Calculator implements MathOperations
{
    @Override
    public int calculate(int a, int b)
	{
        return a + b;
    }
 
    int calculate(int a, int b, int c)
	{
        return a + b + c;
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Calculator calculator = new Calculator();
        System.out.println("Sum of Two Numbers : " + calculator.calculate(4, 7));
        System.out.println("Sum of Three Numbers : " + calculator.calculate(10, 20, 30));
    }
}

Output

Sum of Two Numbers : 11
Sum of Three Numbers : 60