+-
java – 覆盖抽象方法的默认方法实现
Java-8中不允许以下内容:

public interface Operator { default String call() throws Exception { // do some default things return performOperation(); } String performOperation(); } public abstract class AbstractTestClass { public abstract String call() throws Exception; } public class TestClass extends AbstractTestClass implements Operator { @Override public String performOperation() { // do some operation } }

上面的错误消息无法编译,说明TestClass需要是抽象的或覆盖调用方法.

我当时认为默认方法可以提供必要的覆盖.为什么这不起作用?

我不得不做以下事情:

public interface Operator { default String doCall() throws Exception { // do some default things return performOperation(); } String performOperation(); } public abstract class AbstractTestClass { public abstract String call() throws Exception; } public class TestClass extends AbstractTestClass implements Operator { String call() throws Exception { doCall(); } @Override public String performOperation() { // do some operation } }

这缺乏我正在寻找的干净设计.

我在this问题中看到解决方案是:

public class TestClass extends AbstractTestClass implements Operator { String call() throws Exception { Operator.super.call(); } @Override public String performOperation() { // do some operation } }

但是,该解决方案无法解释为什么编译器不允许上述干净的设计.我想理解推理,并且看看是否有一种方法可以隐藏TestClass中的调用方法.

最佳答案
见JLS §8.4.8.4 Inheriting Methods with Override-Equivalent Signatures:

This exception to the strict default-abstract and default-default conflict rules is made when an abstract method is declared in a superclass: the assertion of abstract-ness coming from the superclass hierarchy essentially trumps the default method, making the default method act as if it were abstract. However, the abstract method from a class does not override the default method(s), because interfaces are still allowed to refine the signature of the abstract method coming from the class hierarchy.

您仍然可以使用该方法的默认实现,只需使用InterfaceName.super.methodName()显式调用它:

public class TestClass extends AbstractTestClass implements Operator { @Override public String call() throws Exception { return Operator.super.call(); } @Override public String performOperation() { // do some operation } }

哦,你的performOperation()方法缺少public关键字和@Override注释.

点击查看更多相关文章

转载注明原文:java – 覆盖抽象方法的默认方法实现 - 乐贴网