Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class whose fields are only accessible to its subclasses (without getters/setters)?

Tags:

java

What I really want is a class with a generic constructor, and when a subclass' identical constructor is invoked, the subclass will have access to the same fields. Here is an example of what I would like to do:

public abstract class Command{
    private Mediator m

    public Command(Mediator med){
       m = med;
    }

    abstract void exec();
}

public class FoobarCommand extends Command{
    public FoobarCommand(Mediator med){
        super(med);
    }

    public void exec(){
        med.doAFoobar()
    }
 }

public static void main(String[] args){
    Mediator m = new Mediator();
    Command c = new FoobarCommand(m);
    c.exec();
}

Obviously this won't work because FoobarCommand doesn't have direct access to Mediator med. So how would you access the med field? I don't want anyone else but the subclasses to have access to it, and "protected" is not an option because I want people to be able to create their own commands (which obviously would be outside the package).

like image 451
Jay Avatar asked Oct 01 '09 16:10

Jay


1 Answers

There is actually no such access modifier, strictly speaking. It's impossible to declare a field (or method/class, for that matter) only accessible to subclasses; the most restrictive modifier you can use is protected, which still allows access to other classes in the parent class' package.

But other than that niggle, protected is the way to go.

Edit: to clarify that protected is an option. To access a protected method, you must be either a subclass or within the same package; you don't have to be both. So a subclass of Command created in a different package would still be able to access (super).m.

like image 109
Andrzej Doyle Avatar answered Nov 04 '22 15:11

Andrzej Doyle