2

假设我们有一个包“p1”:

package p1;

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

...我们还有一个包“p2”:

package p2;

import p1.A;

public class B extends A { }

class Tester {
    static void run() {
        new B().method(); //compile-time error
    }
}

现在,如果我们尝试编译一个完整的示例,我们将停留在标记行并出现编译时错误:编译器只是没有在 B 中看到目标方法。为什么会这样?

4

3 回答 3

3

由于is和的访问修饰符存在,但需要注意的是,对于在 class中,就像类的“私有实体” ,只有“公共实体”可以从任何对象引用,因此会产生编译时错误。A.method()protectedB extends Aprotected B.method()protected method()Bmethod()Bnew B().method()

要使您的代码正常工作,您可以更改访问修饰符。

package p2;

import p1.A;

public class B extends A {

    @Override
    public void method() {
        super.method();
    }
 }
于 2013-09-25T07:33:24.903 回答
0

受保护的方法在所有扩展基类(甚至在层次结构中)或同一包内的类中都是可见的。您正在尝试在其他包和非扩展类中使用方法。

于 2013-09-25T07:24:09.257 回答
0

A protected method of a superclass, becomes private in the subclass. If you really want to call it from anywhere then make it public OR ,if you still want to keep your superclass method protected, make a public method in the subclass that calls the (private, inherited) method, something in the subclass like:

public class B extends A { 
      public void callTheMethod(){
             method();
      }
}

and that can be easily called by test class with

class Tester {
    static void run() {
        new B().callTheMethod(); //works well
    }
}
于 2013-09-25T07:37:12.233 回答