Per fare una classe immutabile, quello che posso fare è:fare una classe immutabili in Java
1) Fai classe finale
2) non forniscono setter
3) contrassegnare tutte le variabili come definitiva
ma se la mia classe ha un altro oggetto di qualche altra classe quindi, somone può cambiare il valore di tale oggetto
class MyClass{
final int a;
final OtherClass other
MyClass(int a ,OtherClass other){
this.a = a;
this.other = other;
}
int getA(){
return a;
}
OtherClass getOther(){
return other;
}
public static void main(String ags[]){
MyClass m = new Myclass(1,new OtherClass);
Other o = m.getOther();
o.setSomething(xyz) ; //This is the problem ,How to prevent this?
}
}
non scrivere il metodo impostato –
@LuiggiMendoza, penso che Other/OtherClass è pensato per essere una classe che non controlla. –
Scrivi un wrapper per l'altra classe e crea solo i getter. – Nican