所以,我们有
public abstract class A{
protected abstract String f();
}
public class B extends A{
protected String f(){...}
}
public class C extends A{
protected String f(){
A b = (A) Class.forName("B", true, getClass().getClassLoader()).newInstance();
return b.f();
}
Run Code Online (Sandbox Code Playgroud)
这不允许我访问b.f(),说它B.f()在受保护的范围内,但f受到保护A,并且自C扩展以来A,它也应该可以访问f().
我从子类调用超类'受保护的方法.为什么这种方法"不可见"?
我一直在读一些职位如这一个,这似乎违背了以下内容:
超级课程:
package com.first;
public class Base
{
protected void sayHello()
{
System.out.println("hi!");
}
}
Run Code Online (Sandbox Code Playgroud)
子类:
package com.second;
import com.first.Base;
public class BaseChild extends Base
{
Base base = new Base();
@Override
protected void sayHello()
{
super.sayHello(); //OK :)
base.sayHello(); //Hmmm... "The method sayHello() from the type Base is not visible" ?!?
}
}
Run Code Online (Sandbox Code Playgroud) 我想从提供此受保护方法的类的子类中调用另一个实例的受保护方法.请参阅以下示例:
public class Nano {
protected void computeSize() {
}
}
public class NanoContainer extends Nano {
protected ArrayList<Nano> children;
}
public class SomeOtherNode extends NanoContainer {
// {Nano} Overrides
protected void computeSize() {
for (Nano child: children) {
child.computeSize(); // << computeSize() has protected access in nanolay.Nano
}
}
}
Run Code Online (Sandbox Code Playgroud)
javac告诉我computeSize() has protected access in Nano.我看不出这个的原因(我以为我已经在其他一些代码中这样做了).我想保护这种方法,我该怎么办?
javac version "1.7.0_09"
Run Code Online (Sandbox Code Playgroud)
我想提供一个精简版本,但我没有想到这样的事实,即这些类位于不同的包中.
nanolay.Node
nanolay.NanoContainer
nanogui.SomeOtherNode
Run Code Online (Sandbox Code Playgroud)