Jan Tacci
Jan Tacci

Reputation: 3201

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. 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:

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:

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.

Why is it that I can access the protected member actionId (contained in the base class MyAction) of the instance of MyAction1? 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?

Upvotes: 0

Views: 10722

Answers (2)

Malwaregeek
Malwaregeek

Reputation: 2274

Protected access modifier allows access in the same package + sub classes in other packages.You can remember it as default access plus inheritance.

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

The protected keyword makes things visible within the same package. Which is the case, because both of your classes are in package mypackage.

Here is a nice table, taken from Oracle.com:

enter image description here

Upvotes: 1

Related Questions