简体   繁体   English

访问扩展了抽象基类的类实例的受保护变量?

[英]Accessing Protected Variable Of An Instance Of A Class That Extends An Abstract Base Class?

I have an abstract class called MyAction which contains a protected enum variable. 我有一个名为MyAction的抽象类,其中包含一个受保护的枚举变量。 The class is defined as follows: 该类的定义如下:

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;
    }    
    ...
    ...
}

I created a specific action, MyAction1, that extends MyAction: 我创建了一个特定的动作MyAction1,该动作扩展了MyAction:

package mypackage;

public class MyAction1 extends MyAction {
    public MyAction1() {
        super(ActionId.ACTION1);
    }
    ...
    ...
}    

I have a singleton utility class (in the same package) that creates an instance of MyAction1 and stores it in a HashMap: 我有一个单例实用程序类(在同一包中),该类创建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;
    }    
    ...
    ...
}

Note that in the method actions.put( myAction1.actionId , myAction1) I am able to access the protected member actionId . 请注意,在action.put( myAction1.actionId ,myAction1)方法中我可以访问受保护的成员actionId

Why is it that I can access the protected member actionId (contained in the base class MyAction ) of the instance of MyAction1 ? 为什么我能MyAction1实例的访问受保护的成员actionId(包含在基类MyAction)? I thought protected members were only accessible to subclasses. 我认为受保护的成员只能访问子类。

Does it have anything to do with MyActionFactory being in the same package as the others? MyActionFactory与其他软件包位于同一软件包中有什么关系吗?

The protected keyword makes things visible within the same package. protected关键字使事物在同一包中可见。 Which is the case, because both of your classes are in package mypackage . 之所以如此,是因为您的两个类都在package mypackage

Here is a nice table, taken from Oracle.com : 这是一个很好的表格,取自Oracle.com

在此处输入图片说明

受保护的访问修饰符允许在同一个包中访问+在其他包中的子类。您可以将其记住为默认访问加继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM