在Java中显式调用默认方法

问题描述 投票:196回答:4

Java 8引入了default methods,以提供扩展接口的能力,而无需修改现有的实现。

我想知道,当该方法被覆盖或由于不同接口中的冲突默认实现不可用时,是否可以显式调用方法的默认实现。

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

class B implements A {
    @Override
    public void foo() {
        System.out.println("B.foo");
    }
    public void afoo() {
        // how to invoke A.foo() here?
    }
}

考虑到上面的代码,你如何从B类方法中调用A.foo()

java inheritance interface java-8 default-method
4个回答
271
投票

根据this article,您可以使用接口A访问默认方法

A.super.foo();

这可以使用如下(假设接口AC都有默认方法foo()

public class ChildClass implements A, C {
    @Override    
    public void foo() {
       //you could completely override the default implementations
       doSomethingElse();
       //or manage conflicts between the same method foo() in both A and C
       A.super.foo();
    }
    public void bah() {
       A.super.foo(); //original foo() from A accessed
       C.super.foo(); //original foo() from C accessed
    }
}

AC都可以使用.foo()方法,并且可以选择特定的默认实现,或者您可以使用一个(或两者)作为新foo()方法的一部分。您还可以使用相同的语法来访问实现类中其他方法的默认版本。

可以在chapter 15 of the JLS中找到方法调用语法的形式描述。


14
投票

下面的代码应该有效。

public class B implements A {
    @Override
    public void foo() {
        System.out.println("B.foo");
    }

    void aFoo() {
        A.super.foo();
    }

    public static void main(String[] args) {
        B b = new B();
        b.foo();
        b.aFoo();
    }
}

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

输出:

B.foo
A.foo

7
投票

这个答案主要是针对那些来自45047550问题的用户而写的。

Java 8接口介绍了多重继承的一些方面。默认方法具有已实现的函数体。要从超类调用方法,可以使用关键字super,但如果要使用超级接口进行此操作,则需要明确命名。

class ParentClass {
    public void hello() {
        System.out.println("Hello ParentClass!");
    }
}

interface InterfaceFoo {
    default public void hello() {
        System.out.println("Hello InterfaceFoo!");
    }
}

interface InterfaceBar {
    default public void hello() {
        System.out.println("Hello InterfaceBar!");
    }
}

public class Example extends ParentClass implements InterfaceFoo, InterfaceBar {
    public void hello() {
        super.hello(); // (note: ParentClass.super is wrong!)
        InterfaceFoo.super.hello();
        InterfaceBar.super.hello();
    }

    public static void main(String[] args) {
        new Example().hello();
    }
}

输出:

你好ParentClass! 你好InterfaceFoo! Hello InterfaceBar!


3
投票

您不需要覆盖接口的默认方法。只需将其称为如下:

public class B implements A {

    @Override
    public void foo() {
        System.out.println("B.foo");
    }

    public void afoo() {
        A.super.foo();
    }

    public static void main(String[] args) {
       B b=new B();
       b.afoo();
    }
}

输出:

A.foo

© www.soinside.com 2019 - 2024. All rights reserved.