是否可以使用默认方法实现在基类中实现抽象方法 [英] Can a default method implementation be used to implement an abstract method in a base class

查看:118
本文介绍了是否可以使用默认方法实现在基类中实现抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带抽象方法的类:

If I have a class with an abstract method:

abstract class Base {
    abstract void foo();
}

以及使用默认实现声明相同方法的接口:

and an interface that declares the same method with a default implementation:

interface Inter {
     default void foo() {
         System.out.println("foo!");
     }
}

我是否需要在类中提供实现实现/扩展两者?

do I need to provide an implementation in a class that implements/extends both?

class Derived extends Base implements Inter {

}

看起来这应该可行,但我收到一个编译错误,派生不是抽象的,不会覆盖抽象方法 foo

It seems like this should work, but I get a compilation error that Derived is not abstract and does not override the abstract method foo.

我猜这个抽象方法来自该类比界面中的默认方法更重要。

I am guessing that the abstract method from the class is "more important" than the default method from the interface.

是否有一种很好的方法可以使其工作?

Is there a good way to make this work?

我的根本问题是我有一个三级抽象类层次结构( A B extend C D E extend F C F extend G ),它将具有叶类的多个实现。在每组实现中,有一些常用的方法在基类中定义,所以我希望写一下

My underlying problem is that I have a three level abstract class hierarchy (A and B extend C, D and E extend F, C and F extend G), which will have multiple implementations of the leaf classes. Within each set of implementations, there are common methods being implemented that are defined in the base classes, so I hoped to write

abstract class C extends G {
     abstract void foo();
     abstract void bar();
     abstract void quz();
     void baz() {
         foo();
         bar();
     }
}

abstract class A extends C {
    void quz() { /* impl */ }
}
abstract class B extends C {
    void quz() { /* different impl */ }
}

interface C1 {
     default void foo() { /* impl for first set of classes */ }
}
class A1 extends A implements C1 {
     @Override void bar() { ... }
     // foo implementation from C1
}
class B1 extends B implements C1 {
     @Override void bar() { ... }
}

interface C2 {
     default void foo() { /* impl for second set of classes */ }
}
class A2 extends A implements C2 {
     @Override void bar() { ... }
     // foo implementation from C2
}
class B2 extends B implements C2 {
     @Override void bar() { ... }
}


推荐答案

只需从具体类中调用默认方法:

Just call the default method from your concrete class:

@Override
public void foo() {
    Inter.super.foo();
}

这篇关于是否可以使用默认方法实现在基类中实现抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆