我有一个名为MyAction的抽象类,它包含一个受保护的枚举变量。该类定义如下:
package mypackage;
public abstract class MyAction {
public enum ActionId {
ACTION1, ACTION2;
}
protected ActionId actionId;
// constructor
public MyAction(ActionId actionId) {
this.actionId = actionId;
}
public ActionId getActionId() {
return actionId;
}
...
...
}
我创建了一个特定的动作MyAction1,它扩展了MyAction:
package mypackage;
public class MyAction1 extends MyAction {
public MyAction1() {
super(ActionId.ACTION1);
}
...
...
}
我有一个单例实用程序类(在同一个包中),它创建一个MyAction1实例并将其存储在HashMap中:
package mypackage;
public class MyActionFactory {
private static MyActionFactory theInstance;
private HashMap<ActionId, MyAction> actions;
private MyActionFactory() {
actions = new HashMap<ActionId, MyAction>();
MyAction1 myAction1 = new MyAction1();
actions.put(myAction1.actionId, myAction1); // able to access protected variable actionId
}
public static VsActionFactory getInstance() {
if (theInstance == null)
theInstance = new VsActionFactory();
return theInstance;
}
...
...
}
请注意,在方法 actions.put( myAction1.actionId ,myAction1)中,我可以访问受保护的成员 actionId 。< / p>
为什么我可以访问 MyAction1 实例的受保护成员 actionId (包含在基类 MyAction 中)?我认为受保护的成员只能访问子类。
与 MyActionFactory 与其他包在同一个包中是否有任何关系?
答案 0 :(得分:0)
答案 1 :(得分:0)
受保护的访问修饰符允许访问其他包中的相同包+子类。您可以将其记住为默认访问和继承。