我有一个名为 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;
}
...
...
}
我创建了一个扩展 MyAction 的特定操作 MyAction1:
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。
为什么我可以访问 MyAction1 实例的受保护成员actionId(包含在基类MyAction中) ?我认为受保护的成员只能由子类访问。
这与MyActionFactory与其他人在同一个包中是否有任何关系?