Java Protected Fields VS Public Getters

Java protected fields vs public getters

If there's going to be a public getter anyway, why would you want to expose the field itself more widely than absolutely necessary? That means it's immediately writable by subclasses (unless it's final to start with).

Personally I like all my fields to be private: it provides a cleaner separation between API and implementation. I regard the relationship between a superclass and a subclass as similar to that of a caller and callee - changes to the underlying implementation shouldn't break subclasses any more than they should break callers. The name of a field is an implementation detail which shouldn't impact other classes.

Admittedly my view is occasionally seen as somewhat extreme...

Java : Accessor methods vs protected fields

When you only define methods to access a field, you are restricted by the methods. You cannot do something that there is not a method for.

Consider this class:

public class Account {
private int balance = 0;

public int getBalance() {
return balance;
}

public void insert(int amount) {
if(amount > 0) {
balance += amount;
}
}

public void withdraw(int amount) {
if(amount > 0 && amount =< balance) {
balance -= amount;
}
}
}

You can change the balance of the account by inserting and withdrawing, and you can check what it is. But if you had access to the balance directly, you could do something that is not supposed to be possible like:

Account acc = new Account();
acc.balance = -10;

Furthermore, protected is actually closer to public than to private. If you have a private field, it will be private forever. If your field is protected, anyone can always extend your class and access the field. If it is intended to be private and you set it to protected, it might lose its purpose when someone extends it (and the fact that he extended no longer makes sense, because his new class does not behave in the spirit of the superclass).

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

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.

Java abstract class: protected fields or public set/get methods

Well, it's in part subjective (depends on the scenario) and part preference. I personally never open the fields even to the children classes. Preferring private fields with protected (or public, as needed) getters and setters have helped me a great deal in the past. While it adds a few more characters to code, and makes the code look a little less intuitive, I can list a few pros of my preferred approach that may convince you to start using getters/setters with private fields:

  1. Better control: The parent class knows exactly what changed and what was accessed. Instead of a child class (or grand child) directly modifying the fields, they have to use the setters, giving the parent class the visibility that might come handy some day

  2. Better flexibility: the parent class has the flexibility to change how the fields are maintained, possibly calculated or even refactores significantly without imoacting any of the children classes as long as the signatures of the getter/setters are preserved.

  3. Logging, data access and validations: the getter/setter methods can have programmatic logic to log or check for the data type or perform validations before or after the access or modification. You may be able to add business logic to ensure the caller has access to reading or writing to the fields.

  4. Better description: methods can be documented better (JavaDocs of methods can be made much more explanatory than the same of the member variables)

Hope this helps.

What is the difference between public, protected, package-private and private in Java?

The official tutorial may be of some use to you.

















































ClassPackageSubclass
(same pkg)
Subclass
(diff pkg)
World
public+++++
protected++++
no modifier+++
private+

Confusion on when to use private vs protected fields

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.

Java - protected 'getters' vs. nested classes

The most easiest solution is make the superclass fields or instance variables protected, however, if you make them private you can always access them through getters and setters which conceptually is much more better because it adheres to the principle of encapsulation.



Related Topics



Leave a reply



Submit