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;
in the constructor to set that private 开发者_开发知识库field? I'm just weary since I'm not good with the whole referencing part of 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.
精彩评论