You could use the final keyword.
The you can assign it once.
e.g
public class Exampleclass
{
public final Something something;
void Exampleclass(Something init) {
this.something = init;
}
}
However the content of Something still could be changed, so you may consider returning a clone() of something. (see the class java.util.Date, you still could set the timestamp, in such cases only clone() or a copy constructor helps) . But if your code is not a public lib, then you can leav that getter with clone() away
public class Exampleclass
{
private Something something;
void Exampleclass(Something init) {
this.something = init;
}
void Something getSomething() {
return something.clone();
}
}
But that depends on Something.
Another soultion is a Factory Pattern
, such that only the Factory
can create Something
.
Then there is no public constructor
in Something
. Only the factory can create it.
public class Something() {
private int value;
protectectd Something(int value) {
this.value = value;
}
public tostring() {
System.out.println("values = " + value);
}
}
public class SomethingFactory() {
protected static Someting createSomething(int value) {
return new Something(value);
}
}
USage:
Something some = SomethingFactory.createSomething(3);
But read more by search "java Deisgn Patterns Factory" or FactoryPattern