在java 8中,为什么不能调用当前类正在实现的接口静态方法 [英] In java 8, why cannot call the interface static method that the current class is implementing

查看:1125
本文介绍了在java 8中,为什么不能调用当前类正在实现的接口静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在玩Java 8的新功能并观察到一个有趣的行为:

I'm playing around Java 8's new features recently and observed an interesting behaviour:

这没关系:

Class A { static void staticMethodInA() {println();} }
Class B extends A {}

B.staticMethodInA();






这会导致错误:静态方法只能在包含接口类上调用

interface A { static void staticMethodInA() {println();} }
Class B implements A {}

B.staticMethodInA(); // from here IntelliJ complaints..

有人能告诉我为什么Java 8的设计师可能会选择以不同方式对待上述两种情况?

Can someone tell me why the designer of Java 8 may choose to treat the above 2 cases differently?

推荐答案

添加 static 方法Java 8中的接口带有1个限制 - 这些方法不能由实现它的类继承。这是有道理的,因为一个类可以实现多个接口。如果2个接口具有相同的 static 方法,则它们都将被继承,编译器将不知道要调用哪个。

Addition of static methods in interface in Java 8 came with 1 restriction - those methods cannot be inherited by the class implementing it. And that makes sense, as a class can implement multiple interface. And if 2 interfaces have same static method, they both would be inherited, and compiler wouldn't know which one to invoke.

但是,通过扩展课程,这没有问题。 static 类方法由子类继承。

However, with extending class, that's no issue. static class methods are inherited by subclass.

参见 JLS§ 8.4.8


C类从其直接超类继承超类的所有具体方法m(静态和实例)

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass

...

C类继承自其直接超类和直接超接口所有抽象和默认(§9.4)方法m

A class C inherits from its direct superclass and direct superinterfaces all abstract and default (§9.4) methods m

.. 。

不会从其超接口继承静态方法

这篇关于在java 8中,为什么不能调用当前类正在实现的接口静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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