与私有方法冲突时在接口中调用默认方法 [英] Calling default method in interface when having conflict with private method

查看:182
本文介绍了与私有方法冲突时在接口中调用默认方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的类层次结构。

Consider below class hierarchy.

class ClassA {
    private void hello() {
        System.out.println("Hello from A");
    }
}

interface Myinterface {
    default void hello() {
        System.out.println("Hello from Interface");
    }
}

class ClassB extends ClassA implements Myinterface {

}

public class Test {
    public static void main(String[] args) {
        ClassB b = new ClassB();
        b.hello();
    }
}

运行程序会出现以下错误:

Running the program will give following error :

Exception in thread "main" java.lang.IllegalAccessError: tried to access method com.testing.ClassA.hello()V from class com.testing.Test
at com.testing.Test.main(Test.java:23)




  1. 这都是因为我将ClassA.hello标记为私有。

  2. 如果我将ClassA.hello标记为受保护或删除可见性修饰符(即将其设为默认值)范围),然后它显示编译器错误:
    继承的方法ClassA.hello()无法隐藏Myinterface中的公共抽象方法

  1. This is all because I marked ClassA.hello as private.
  2. If I mark ClassA.hello as protected or remove the visibility modifier(i.e. making it default scope), then it shows a compiler error as : The inherited method ClassA.hello() cannot hide the public abstract method in Myinterface

但是,根据上面的异常堆栈跟踪,我得到一个运行时IllegalAccessError。

However, as per exception stacktrace above, I get a runtime IllegalAccessError.

我无法理解为什么在编译时没有检测到这一点。有什么线索?

I couldn't get why this is not detected at compile time. Any clues ?

推荐答案

更新:好像它确实是 错误

Update: Seems like it's really a bug.

A class或超类方法声明总是优先于默认方法!

A class or super-class method declaration always takes priority over a default method!

默认hello(...)来自 Myinterface 的方法允许你写错误:

default hello(...) method from the Myinterface allows you to write without errors:

ClassB b = new ClassB();
b.hello();

直到运行时,因为在运行时 hello(...) ClassA 的c $ c>方法具有最高优先级(但该方法是私有的)。因此, IllegalAccessError 发生。

Until runtime, because at runtime hello(...) method from the ClassA takes the highest priority (but the method is private). Therefore, IllegalAccessError occurs.

如果删除默认的 hello(...) 方法从接口,你得到相同的非法访问错误,但现在在编译时。

If you remove the default hello(...) method from the interface, you get the same illegal access error, but now at compile time.

这篇关于与私有方法冲突时在接口中调用默认方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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