有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当使用继承时,访问修饰符在哪些情况下会有所不同?

我已经使用Java有一段时间了,基本上是自学的。但我对访问修饰符有点困惑,这让我感到困扰,因为我本周晚些时候要参加OCA考试,这是我唯一不太擅长的话题
如果我们有一个具有受保护方法的类,并且我们扩展该类并使用public重写该方法,那么就可以了。我们从一个受保护的方法变成了一个公共方法。我的问题是,在其他什么情况下访问修饰符可以不同

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    确切的规则由JLS 8.4.8.3. Requirements in Overriding and Hiding给出

    The access modifier of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

    • If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
    • If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
    • If the overridden or hidden method has package access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

    一定是这样。如果您可以用更严格的访问权限覆盖方法,这将违反Liskov可替换性原则(LSP)。LSP说,只要可以使用超类型的实例,就应该能够使用子类型的实例