[英]How can I implement interface correctly?
我正在做一個使用 java 和 java 接口的簡單計算器的作業。 但是實現 java 的 class 給出錯誤提示
The public type `BasicCalculator` must be defined in its own file
The type `BasicCalculator` must implement the inherited abstract method `calculate.mul(int, int)
這是代碼
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);
}
}
這里有幾個問題。
首先,由於BasicCalculator
是一個公共 class,因此需要在其自己的名為BasicCalculator.java
的文件中定義它。
其次, BasicCalculator
中的方法名稱必須與您嘗試在calcualte
中實現的方法名稱相匹配——即sub
、 mul
和div
而不是subtract
、 multiply
和division
。
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.
然后在您已實現的每個方法之上添加@Override,以便代碼將 go 為:
@Override
public int div(int a, int b) {
return 0;
}
像這樣的例子。
這里發生的事情是因為您正在實現您的接口,您需要在您正在實現的 class 中擁有所有方法。
最后,當你運行 test.java 時,添加 System.out.println(c.add(5, 6)); 例如,因為返回 x; 不在控制台上打印實際值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.