Skip to content
Advertisement

How can I implement interface correctly?

I am doing homework of making a simple calculator using java and interface in java. but the class that implements java gives error saying

The public type `BasicCalculator` must be defined in its own file
        The type `BasicCalculator` must implement the inherited abstract method `calculate.mul(int, int)

here is the code

interface calculate{
    public int add(int a, int b);
    public int sub(int a, int b);
    public int mul(int a, int b);
    public int div(int a, int b);
}

public class BasicCalculator implements calculate { 
    public int a;
    public int b;

    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }

    public int multiply(int a, int b) {
        return a * b;
    }

    public int division(int a, int b){
        return a/b;
    }
}

public class test {
    public static void main(String[] args) {
        calculate c= new BasicCalculator();
        c.add(5,6);
    }
}

Advertisement

Answer

There are a couple of issues here.

First, since BasicCalculator is a public class, it needs to be defined in its own file named BasicCalculator.java.

Second, the method names in BasicCalculator must match those you’re trying to implement in calcualte – i.e., sub, mul and div instead of subtract, multiply and division.

Advertisement