如何在java类中编写Immutable类? [英] How to write Immutable class in java like the String class?

查看:77
本文介绍了如何在java类中编写Immutable类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在java中编写Immutable类,比如String类?



我想用new关键字创建该类的对象并调用构造函数

在String中我们可以创建为



String s =Sunil;

解决方案

请参考:



http:/ /docs.oracle.com/javase/tutorial/ [ ^ ]



请提供代码并询问具体情况。

这是一项家庭作业,我们还没有做好准备。我们希望你能够完成这项任务,这样你就可以学习它。


不可变的课程:

1.所有领域都是私人决赛。

2.现在在构造之后修改对象。

3.必须构造对象,可能必须初始化所有字段。

4.课程必须是最终的。

例如:

  public  最终  ImmutableClass {

private final int field1;
private final String field2 ;

public ImmutableClass( int _1, String _2){
this .field1 = _1;
.field2 = _2;
}

public int getfield1(){
return field1;
}

public String getfield2(){
return field2;
}
}



请注意,没有set方法,修改字段的唯一方法是使用构造函数。阅读更多此处


How we can write Immutable class in java like the String class?

I want to create an object of that class with out the new keyword and calling the constructor
as such in String we can create as

String s = "Sunil";

解决方案

Please refer here:

http://docs.oracle.com/javase/tutorial/[^]

and please provide code and ask specific.
This is a homework task, which we are not making ready. We'd like YOU to work that task so you can learn it.


Immutable classes:
1. All fields is private final.
2. Noway to modify the object after construction.
3. Object must be constructed probably that all fields must be initialized.
4. the class must be final.
For example:

public final class ImmutableClass{

    private final int field1;
    private final String field2;

    public ImmutableClass(int _1, String _2) {
        this.field1 = _1;
        this.field2 = _2;
    }
  
    public int getfield1(){
        return field1;
    }
  
    public String getfield2(){
        return field2;
    }
}


Note that there are no set method and the only way to modify the fields is using constructor. Read more here


这篇关于如何在java类中编写Immutable类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆