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?
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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With