[英]Abstract methods do not specify a body - Interface trying to implement super interface method giving compile time error in JDK 8
我目前正在尝试学习JDK 8
功能及其新功能,我们可以在接口内部执行方法。 像这样
interface SuperInt {
public static void method1() { // completely qualified
System.out.println("method1");
}
public default void method2() { // completely qualified
System.out.println("method2");
}
public void method3(); // completely qualified
}
但是,当我尝试扩展此接口并尝试在子接口中实现它时,会产生编译时错误。
抽象方法不指定正文
interface SubInt extends SuperInt {
public void method3() { // compile time error
}
}
如果可以在接口中保留已实现的方法,那么为什么在我们尝试在其子接口中实现超级接口的abstarct方法时会出错呢?
但是,当我尝试扩展此接口并尝试在子接口中实现它时,会产生编译时错误。
您没有尝试实现它,相反,您正在定义一个新的抽象方法。
public void method3() { // compile time error
}
如果要提供实现,则在方法声明前面加上default
关键字:
public default void method3() { // compile time error
...
}
您无法在interface
实现抽象方法,而SubInt
仍然是interface
而不是class
interface SubInt extends SuperInt
正在尝试扩展接口而不是实现它。 要实现它,你应该使用
public class SuperIntImpl implements SuperInt {
@Override
public void method3() {
}
}
另一方面, method2
是一个default
方法,这就是它与实现一起编译的原因。
相关的例子SubInt
和SuperInt
在默认覆盖实现SubInt
,希望这个例子将澄清的事情:
public interface SuperInt {
void method3();
void method4();
}
public interface SubInt extends SuperInt {
@Override
default void method3() {
System.out.println("Inside SubInt");
}
}
而实现SubInt
现在可以选择覆盖或没有method3
, 这是一个仍然必须实施method4
作为
public class SubIntImpl implements SubInt {
@Override
public void method4() {
}
// can reuse the implementation of the 'method3'
}
并为任何实现SuperInt
它仍然是一个必须有它自己的实现二者的method3
和method4
public class SuperIntImpl implements SuperInt {
@Override
public void method3() {
// must have my own implementation
}
@Override
public void method4() {
// must have my own implementation
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.