我有一个名为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;
    }
    ...
    ...
}


请注意,在方法action.put(myAction1.actionId,myAction1)中,我可以访问受保护的成员actionId。

为什么可以访问MyAction1实例的受保护成员actionId(包含在MyAction基类中)?我认为受保护的成员只能访问子类。

与MyActionFactory与其他软件包位于同一软件包中有什么关系吗?

最佳答案

protected关键字使事物在同一包中可见。之所以如此,是因为您的两个类都在package mypackage中。

这是一个很好的表格,取自Oracle.com

07-26 05:34