Java - 无法访问由嵌套类扩展的超类的受保护方法

问题描述 投票:0回答:3

我是 Java 新手,正在掌握受保护的可见性的窍门。

我有一个类 A,其受保护方法 method1 如下 -

public abstract class A { 
    public A(...){}

    protected void method1(){
        // do something
    }

现在我有另一个 B 类,它扩展了一个不同的 C 类。B 类有一个嵌套静态类,D 类扩展了 A 类

public class B extends C {
    public B(...){
        super(...);
    }

    private static class D extends A {
        D(...){super(...);}
    }

    public void method2() {
        D record = new D();
        record.method1(); // need to access the protected method1 of class A, which is the superclass of nested class D. Getting the error here
    }
}

我收到此错误 - method1 在 A 类中具有受保护的访问权限 现在我的问题是如何访问method1?我无法在 A 类中将其更改为公共

java inheritance inner-classes protected
3个回答
3
投票

您需要在 D 类中创建一个代理方法,如下所述。 D类可以访问A类的受保护方法,但是D类的实例不能直接调用受保护方法,必须有代理方法才能调用超类的受保护方法。

在D类中,需要为A类中的方法创建一个公共getter,所以:

public class A {
    protected void protectedMethod() {}
}

public class D extends A {
    public void callProtectedMethod() {
        super.protectedMethod();
    }
}

final D record = new D();

record.callProtectedMethod();

0
投票

由于 A.method1() 受到保护,因此只能从 A 的同一类/同一包/子级访问它。

在您的代码中,您正在 B 中调用 A.method1(),如果 B 与 A 不在同一包中,则无法访问该方法

解决方案是使用包装器作为 @Alex Ander 或将 A.method1() 的修饰符更改为 public


0
投票

问题是由

method1()
调用的受保护的
method2()
引起的,它属于B,位于A和D之外,并且B与A或D不在同一个包中。

method1()
只能在A或D内部使用/调用。这就是
protected
的用途,以确保它仅在所有者类、其继承类或同一包中使用。

这就是为什么当在 D 内部创建包装方法时,问题就解决了,因为受保护的

method1()
是从 D 内部调用的。

我们仍然可以覆盖 A 受保护的

method1()
并在必要时通过 D 将其公开。 (根据上面的包装示例修改)

class A {
    protected void protectedMethod() {}
}

class D extends A {
    @Override
    public void protectedMethod() {
        super.protectedMethod();
    }
}

final D record = new D();
record.protectedMethod();
© www.soinside.com 2019 - 2024. All rights reserved.