class X
{
String x1;
String x2;
//...
String x15;
public X (Other o)
{
// initialize x1,x2,...,x15
}
String getx1 () { return x1; } // lot of getters
String getx2 () { return x2; }
//...
String getx15 () { return x15; }
}
The object of class X is initialized in constructor of class Other;
class Other
{
private X obj;
// Other members
public Other ()
{
obj = new X(this);
//...
}
//...
}
I want to somehow get rid of lot of getter methods in class X. I can simply remove those and make all the data members of X in default scope (X is used only within package).
Is there any way by which I can make the members of X obj un-mutable after the constructor Other is called ? Here the idea is, when using get() methods, the variables inside X cannot be modified.
obj.getx1();
Now, if I use simply obj.x1 then there are chances that it might get overwritten (or at least in code review, it will be objected).
[Note: obj has to be initialized in the Other() constructor only].
Best way to make a class immutable (not un-mutable) is to mark all fields as
final(visibility is irrelevant, can bepublic). Fields must be initialized either with an initializer:or in every constructor: