6

Disregarding the fact that making variables protected can be convenient, is there anything that actually necessitates the existence of protected?

Steve P.
  • 14,489
  • 8
  • 42
  • 72

3 Answers3

16

Even if you use getters and setters (which I personally would - I almost always keep fields private) that doesn't mean that protected becomes pointless... it just means that you're likely to make the getters and setters themselves protected rather than the variable.

If your question is really about whether protected accessibility is useful at all, I'd say it is - it often makes sense to have a member which is only accessible to subclasses. More than that, I sometimes use a protected abstract method to which is called by the superclass, but isn't accessible outside the hierarchy.

For example, in the template method pattern you may well have a public method which does some setup, calls a protected abstract method, and then perhaps does some final work too. You don't want the abstract method to be public, because you want to make sure your start/end code is executed... and you don't want to force that code to be called by subclasses explicitly.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Consider you want to make a class car which contains a variable fuel. You don't want this variable be set from outside directly, because fuel usage depends on the car. However, if someone extends car, they should be able to modify it.

class Car {
    protected float fuelLevel;
    public float getFuel() { 
        return this.fuelLevel;
    }
    public void drive() {
        this.fuelLevel -= 0.5; // fuel usage of an average car
    }
}


class Ferrari extends Car {
    public void drive() { // override drive method
        this.fuelLevel -= 2; // obviously, a Ferrari consumes much more fuel!
    }
}

You could also do the same with a protected void setFuel(...) method.

Uooo
  • 6,204
  • 8
  • 36
  • 63
0

protected properties can be marked abstract or can be marked virtual and overridden. Using a variable instead of a property prevents this and forces derived classes to directly use the base class' implementation.

Monstieur
  • 7,992
  • 10
  • 51
  • 77