字符串作为新类的唯一私有字段

发布于 2024-10-15 14:59:54 字数 143 浏览 1 评论 0原文

这里的一般问题:如果我正在创建一个新类,并且它的唯一私有字段是一个字符串,我可以在构造函数中执行类似 this.privateString = argumentIn; 的操作来设置该私有字段吗?我只是累了,因为我不擅长 java 的整个引用部分。

General question here: If I'm making a new class, and it's only private field is a string, can I do something like this.privateString = argumentIn; in the constructor to set that private field? I'm just weary since I'm not good with the whole referencing part of java.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

下壹個目標 2024-10-22 14:59:54

,因此私有字段的定义只能从类本身内部访问。

作为提示,如果没有任何访问器,这可能会使此类的对象几乎毫无用处。

Yes, and thus the definition of a private field being only accessible from within the class itself.

And as a tip, without any accessors, this may render your objects of this class mostly useless.

記憶穿過時間隧道 2024-10-22 14:59:54

确实。考虑这个例子。我添加了一些基本的防御性复制练习。

/**
* MyClass is an immutable class, since there is no way to change
* its state after construction.
*/

public final class MyClass{

private final String myString;

public MyClass(String myString){
   this.myString = myString;
}

 /**
  * Returns an immutable object. String is immutable.
  *
  */

public String getMyString(){
   return myString;
}

//no need to provide a setter to keep myString as immutable after initial state
}

考虑阅读 Joshua Bloch 撰写的关于字段的防御性复制。

Definitely. Consider this example. I have added some basic defensive copying practice.

/**
* MyClass is an immutable class, since there is no way to change
* its state after construction.
*/

public final class MyClass{

private final String myString;

public MyClass(String myString){
   this.myString = myString;
}

 /**
  * Returns an immutable object. String is immutable.
  *
  */

public String getMyString(){
   return myString;
}

//no need to provide a setter to keep myString as immutable after initial state
}

Consider reading this post by Joshua Bloch on defensive copying of fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文