java - Why use getters instead of public fields in immutable objects? -


this question has answer here:

i aware using getters , making fields private has many advantages in general cases (data-hiding, decoupling, blah, blah, blah). i'm asking related immutable classes.

let's i've created model class store data rest response, example:

public final class profile {     private final int id;     private final string name;     private final string info;     private final string location;     private final uri avatar;     private final gender gender;     // 10 more fields } 

the class , fields final , cannot changed or overridden. each field instance of immutable class , validated in constructor. also, every field needs publicly accessible (no data-hiding).

in such case, possible advantage there tripling size of class add getters every field instead of making fields public?

implementing getters provides flexibility future changes profile class. if class provides getter can change underlying private member in profile class , won't require changes consumers of class. want hide data types of class-level variables want hide values.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -