Home >Java >javaTutorial >How to Explicitly Call Default Methods in Java?

How to Explicitly Call Default Methods in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 00:06:23336browse

How to Explicitly Call Default Methods in Java?

Calling Default Methods Explicitly in Java

Java 8 introduces default methods to extend interfaces without modifying existing implementations. However, developers may encounter scenarios where explicitly calling a default implementation is necessary, such as when a method has been overridden or conflicts occur with multiple default implementations in various interfaces.

Consider the following example:

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?
    }
}

To explicitly invoke A.foo() from class B, use the following syntax:

A.super.foo();

This syntax allows you to specify the exact default implementation to be called, resolving potential conflicts or overriding issues. In the example above, afoo() can be implemented as follows:

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

The code within afoo() will now call the default implementation of foo() from interface A, even though it has been overridden in class B.

Additionally, if multiple interfaces define default methods with the same name, you can use the same syntax to choose the specific implementation to be called. For instance, if C is another interface with a default foo() method, then the following code can be used:

public class ChildClass implements A, C {
    @Override    
    public void foo() {
       A.super.foo();
       C.super.foo();
    }
}

This approach allows for flexibility and control over which default implementations are used in your classes. By explicitly calling default methods, you can resolve conflicts and take advantage of the extended capabilities provided by Java 8's default methods without the need to modify existing interface definitions.

The above is the detailed content of How to Explicitly Call Default Methods in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn