在java中使类不可变

为了使类不可变,我能做的是:

1)让课程最终
2)不提供制定者
3)将所有变量标记为final

但是如果我的类有另一个类的另一个对象,那么somone可以改变该对象的值

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?

}
}

解决方法

A)使OtherClass也是不可变的

要么

B)不允许直接访问OtherClass对象,而只提供getter作为代理.

编辑添加:您可以制作OtherClass的深层副本并返回副本而不是原始副本,但这通常不是您在Java中所期望的行为类型.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...