V1rtua1An0ma1y
V1rtua1An0ma1y

Reputation: 627

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.

Upvotes: 2

Views: 136

Answers (2)

CoolBeans
CoolBeans

Reputation: 20800

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.

Upvotes: 1

jerluc
jerluc

Reputation: 4316

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.

Upvotes: 4

Related Questions