Search code examples
javastringmutable

Proper way to construct a Test object with a mutable member variable


What would be the proper way to construct a Test object with a member variable testName?

I want to support the ability to set the value of this attribute when it is constructed, and allow it to be mutable via a setter methods:

public class Test {
    private String testName;

    public Test( String name ) {
        this.testName = name;
    }

    public setTestName( String name ) {
        this.testName = name;
    }
}

Solution

  • To create objects, you call their constructor. In your case, that's Test(String name):

    Test myTestObject = new Test("and you must provide a string as a parameter");
    

    now, because of the implementation of the constructor (this.testName = name;), the object's member value of testName will be "and you must provide a string as a parameter".

    Then you can set it to something different using the setter in the class:

    myTestObject.setTestName("here you also need to provide a string as a parameter");
    

    This way, when the object is constructed, there's some value in testName, and after that it is changed to something else.

    This outlines how you can change the value of testName whenever you want, and to whatever you want. All you need to do is pass the wanted string as a parameter to the function.

    You can read some more info here and here.