java调用类的静态方法,在java 8中,为什么不能调用当前类正在实现的接口静态方法...

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

This is okay:

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

Class B extends A {}

B.staticMethodInA();

This would induce an error of: static method may be invoked on containing interface class only.

interface A { static void staticMethodInA() {println();} }

Class B implements A {}

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

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

解决方案

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.

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

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

...

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

...

A class does not inherit static methods from its superinterfaces.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值