加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在java中使类不可变

发布时间:2020-12-15 00:41:51 所属栏目:Java 来源:网络整理
导读:为了使类不可变,我能做的是: 1)让课程最终 2)不提供制定者 3)将所有变量标记为final 但是如果我的类有另一个类的另一个对象,那么somone可以改变该对象的值 class MyClass{ final int a; final OtherClass other MyClass(int a,OtherClass other){ this.a =
为了使类不可变,我能做的是:

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中所期望的行为类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读