如何在java类中编写Immutable类?

编程入门 行业动态 更新时间:2024-10-25 18:35:00
本文介绍了如何在java类中编写Immutable类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们如何在java中编写Immutable类,比如String类? 我想用new关键字创建该类的对象并调用构造函数 在String中我们可以创建为 String s =Sunil;

解决方案

请参考: http:/ /docs.oracle/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: docs.oracle/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类?

本文发布于:2023-11-22 20:14:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类中   如何在   java   Immutable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!