interface A { int add(); default void sub(){ } } class B implements A { int x, y; B(int x, int y) { x=x; y=y; } int add(int x, int y) { return x+y; } } public class C { public static void main(Str ing[] args) { B b=new B(10, 20); int result=b. add(10, 20); System. out. println(result) ; } }
时间: 2023-12-03 15:02:26 浏览: 27
这段代码存在一些错误和问题,无法正常编译和运行。下面是修正后的代码以及相关的解释:
```
interface A {
int add();
default void sub() { }
}
class B implements A {
int x, y;
B(int x, int y) {
this.x = x;
this.y = y;
}
public int add() { // 接口 A 中的 add 方法需要被实现
return x + y;
}
}
public class C {
public static void main(String[] args) {
B b = new B(10, 20);
int result = b.add();
System.out.println(result);
}
}
```
修改后的代码中,`interface A` 定义了一个 `add()` 方法和一个默认方法 `sub()`。`class B` 实现了接口 `A`,并实现了 `add()` 方法来计算 `x` 和 `y` 的和。需要注意的是,`add()` 方法的签名必须和接口 `A` 中定义的一致。
在 `main()` 方法中,创建了一个 `B` 类的实例 `b`,并调用 `add()` 方法来计算 `x` 和 `y` 的和,并将结果存储在 `result` 变量中。最后,将 `result` 的值输出到控制台。
需要注意的是,如果 `B` 类需要实现 `A` 接口中的默认方法 `sub()`,则需要在 `B` 类中重新实现该方法。在本例中,由于 `B` 类不需要使用到 `sub()` 方法,因此可以不用实现该方法。