Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion on when to use private vs protected fields

I have seen users in SO saying that protected fields are bad, because it can introduce problems as the code grows. Please refer to the following code.

public class Car {
    private String modelName;
    private int yearReleased;

//getters and setters

}

If the Car class is extended by a class named ToyotaCar

public class ToyotaCar extends Car{
   // Toyota specific stuff
}

I want my ToyotaCar object to have a modelName and yearReleased fields. And that is why I decided to extend from Car class. But private members are not inherited by the subclass (even though I could access those fields using a public getter and setter). Now my confusion is whether I should make the fileds in the Car class to protected instead of private. But people say that introduces problems.

Does it mean no matter what class you write always, make the fields private?

If so on what instances the protected keyword is used? is it only for methods which we are planning to use in our subclasses?

like image 995
DesirePRG Avatar asked Apr 11 '15 10:04

DesirePRG


People also ask

When should you make fields private?

Fields should be declared private unless there is a good reason for not doing so. One of the guiding principles of lasting value in programming is "Minimize ripple effects by keeping secrets." When a field is private , the caller cannot usually get inappropriate direct access to the field.

When should a method be protected?

The best time to create a method under the protected heading is when you want to compare and/or transfer data between objects of the same class, but you don't want that information to be made public.

Should you ever use protected?

Should you ever use protected member variables? Depends on how picky you are about hiding state. If you don't want any leaking of internal state, then declaring all your member variables private is the way to go. If you don't really care that subclasses can access internal state, then protected is good enough.

What is the point of private fields?

In Summary private keyword in java allows most restrictive access to variables and methods and offer strongest form of Encapsulation. private members are not accessible outside the class and private method can not be overridden.


1 Answers

You nailed it yourself: a good practice is to make everything 'private' by default. Then, your specific design may require for example to be able to use some attributes or (preferably) some methods inside a subclass. In that situation, you'll need to move them toward 'protected' - but only in that situation.

Remember that using the accessors (getters & setters) is perfectly ok, and can be done without breaking encapsulation.

like image 88
Martin Avatar answered Sep 30 '22 09:09

Martin