有 Java 编程相关的问题?

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

java重写和弱化访问修饰符

根据JLS 8.4.8.1

An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:

  • C is a subclass of A.

  • The signature of m1 is a subsignature (§8.4.2) of the signature of m2.

  • Either:

    • m2 is public, protected, or declared with default access in the same package as C, or

    • m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.

这似乎与以下代码并不矛盾:

public class Main {

    public void f() { }
    public static class A extends Main {
        protected void f() { }
    }

    public static void main(String[] args) {

    }
}

DEMO

但是它不是编译,即使方法f()的重写版本有protected访问修饰符,正如我在提供的规则的第二点中所说的。怎么了


共 (2) 个答案

  1. # 1 楼答案

    不能使用更严格的访问修饰符重写方法。方法f()是用访问修饰符public声明的,但您正试图用protected修饰符覆盖它,后者限制性更强。改变

    public static class A extends Main{
            protected void f(){ }
        }
    

    public static class A extends Main{
            public void f(){ }
        }
    
  2. # 2 楼答案

    这方面的理由在以下JLS中提供8.4.8.3

    The access modifier (§6.6) 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 default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

    请注意,您在问题中引用的部分基本上说明了“基类中方法的访问修饰符不能是私有的”,并且与重写方法的访问修饰符完全无关