Home > Java > javaTutorial > How do you invoke a default method\'s implementation explicitly in Java when it\'s overridden in a class?

How do you invoke a default method\'s implementation explicitly in Java when it\'s overridden in a class?

Mary-Kate Olsen
Release: 2024-11-16 04:34:03
Original
662 people have browsed it

How do you invoke a default method's implementation explicitly in Java when it's overridden in a class?

Invoking Default Methods Explicitly in Java

Java 8 introduced default methods as a way to extend interfaces without breaking existing implementations. However, how do you invoke the default implementation of a method when it's overridden or conflicts with other default implementations?

In the provided code, the foo() method is defined as a default method in the A interface and overridden in the B class. To access the default implementation of A.foo() in the B class, you can use the following syntax:

A.super.foo();
Copy after login

This allows you to invoke the default implementation even though it's been overridden. It's important to note that the A.super reference refers to the A interface type, not the B class object.

public class ChildClass implements A, C {
    @Override
    public void foo() {
        // Override the default implementation
        System.out.println("ChildClass.foo()");
    }

    public void callDefault() {
        // Invoke the A.foo() default implementation
        A.super.foo();
        // Invoke the C.foo() default implementation
        C.super.foo();
    }
}
Copy after login

In this example, the ChildClass implements both the A and C interfaces, each with its own default foo() method. By using A.super.foo() and C.super.foo(), the default implementations can be accessed explicitly, allowing for specific behavior or conflict resolution.

The above is the detailed content of How do you invoke a default method\'s implementation explicitly in Java when it\'s overridden in a class?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template