Java Reference
In-Depth Information
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
The value instance variable defines the state of an IntHolder object. You create an object of the IntHolder class
as shown:
IntHolder holder = new IntHolder(101);
int v = holder.getValue(); // will return 101
At this time, the value instance variable holds 101 , which defines its state. You can get and set the instance
variable using the getter and setter.
// Change the value
holder.setValue(505);
int w = holder.getValue(); // will return 505
At this point, the value instance variable has changed from 101 to 505 . That is, the state of the object has
changed. The change in state was facilitated by the setValue() method. Objects of the IntHolder class are examples
of mutable objects.
Let's make the IntHolder class immutable. All you need to do is to remove the setValue() method from it to
make it an immutable class. Let's call your immutable version of the IntHolder class as IntWrapper , as shown in
Listing 7-16.
Listing 7-16. An Example of an Immutable Class
// IntWrapper.java
package com.jdojo.object;
public class IntWrapper {
private final int value;
public IntWrapper(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
This is how you create an object of the IntWrapper class:
IntWrapper wrapper = new IntWrapper(101);
 
Search WWH ::




Custom Search