Is there any advantage to using protected variables over getters and setters?

Apart from the fact that creating protected variables can be convenient, is there something that actually requires the existence of protected ?

+6
source share
3 answers

Even if you use getters and setters (which I personally would like - I almost always kept the fields private), this does not mean that protected becomes meaningless ... it just means that you will probably make the getters and the settings themselves protected , and not a variable.

If your question is whether protected accessibility is really useful at all, I would say that it is - it often makes sense to have a member available only for subclasses. Moreover, I sometimes use a protected abstract method to which a superclass is called, but is not available outside the hierarchy.

For example, in a template method template, you can have a public method that does some customization, invokes a protected abstract method, and then maybe also does some final work. You do not want the abstract method to be publicly available, because you want to make sure your start / end code is executed ... and you do not want to force subclasses to call this code.

+16
source

Suppose you want to create a car class that contains variable fuel. You do not want this variable to be set directly from the outside, since the use of fuel depends on the car. However, if someone extends a 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 can also do the same with the protected void setFuel(...) method.

+2
source

protected properties may be marked abstract or may 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.

0
source

Source: https://habr.com/ru/post/948292/


All Articles