[英]String as only private field for new class
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;
这里的一般问题:如果我要创建一个新类,并且只有私有字段是一个字符串,我可以做这样的事情
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.
我只是疲倦,因为我对Java的整个引用部分都不满意。
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. 并且提示,没有任何访问器,这可能会使您的此类对象几乎无用。
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 . 考虑阅读Joshua Bloch撰写的有关防御性复制字段的文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.