在Java中显式调用默认方法

编程入门 行业动态 更新时间:2024-10-11 15:17:10
本文介绍了在Java中显式调用默认方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Java 8引入了默认方法来提供扩展接口而不需要修改现有实现的能力。

Java 8 introduces default methods to provide the ability to extend interfaces without the need to modify existing implementations.

我想知道在重写该方法时是否可以显式调用方法的默认实现,或者是不可用,因为不同接口中的默认实现存在冲突。

I wonder if it's possible to explicitly invoke the default implementation of a method when that method has been overridden or is not available because of conflicting default implementations in different interfaces.

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

考虑到上面的代码,你怎么称呼 A.foo()来自B类方法?

Considering the code above, how would you call A.foo() from a method of class B?

推荐答案

按照这篇文章您可以在界面中访问默认方法A 使用

A.super.foo();

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

This could be used as follows (assuming interfaces A and C both have default methods 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 } }

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

A and C can both have .foo() methods and the specific default implementation can be chosen or you can use one (or both) as part of your new foo() method. You can also use the same syntax to access the default versions in other methods in your implementing class.

方法调用语法的形式描述可以在 JLS第15章。

Formal description of the method invocation syntax can be found in the chapter 15 of the JLS.

更多推荐

在Java中显式调用默认方法

本文发布于:2023-11-05 03:10:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559745.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Java   中显式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!