Akhil Gupta Akhil Gupta - 1 year ago 59
Java Question

Access Modifiers in Java when used with Immutable Class

Is it recommended to have public access modifiers for the data fields in final (Immutable) java class, even if the data fields are not the references to mutable datatype Or Shall we access data fields directly as data fields are supposed to be defined in constructor itself hence nullify all chances of changing the internal representation of class.
Please suggest?

For example:

public class MainApp {

public static void main(String args[]) {

Immutablesample immutablesample = Immutablesample.getInstance("akkhil");

System.out.println(" Before modification " + immutablesample.getName());
immutablesample.name = "gupta";
System.out.println(" After modification " + immutablesample.getName());


is the calling code trying to change the data field by accessing it directly(without access modifier) for the following class:

public final class Immutablesample {

private final String name;

private Immutablesample(String name){
this.name = name;

public String getName(){
return name;

public static Immutablesample getInstance(String name){
return new Immutablesample(name);


How would it make the class prone to get its internal representation changed if i change the modifier from private to public
private String name; to public String name;
since the object was creating with parameterized constructor so has immutable data fields, than why is it necessary to make data fields private?

Answer Source

Two simple rules to follow:

  1. Try to make your whole class as "immutable" as you can. For example setting private final fields only via constructors. And when using "incoming" collection objects, consider to create a copy of their content to be really on the safe side.
  2. Keep in mind that good OO is about exposing behavior; not about exposing data. Meaning: you absolutely do not want to make fields public unless you have really good reasons to do so. In other words: you do not want that some other class B does something because of the content of some field in class A. And the way to prevent that: making your fields private!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download