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);
}
}
CodePudding user response:
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
.
CodePudding user response:
Send the test class onto it's own class and not in the same class as BasicCalculator.java, because java usually doesn't like to deal with classes this way unlike C.
Then add @Override on top of each method that you have implemented so the code will go as:
@Override
public int div(int a, int b) {
return 0;
}
like this for example.
The thing that is happening here is since you are implementing your interface you need to have all the methods inside the class that you are implementing in.
And at the end when you run test.java, add System.out.println(c.add(5, 6)); for example since return x; doesn't print the actual value on the console.