Developing Java Beans public void setValue(int value) {
Developing Java Beans public void setValue(int value) { val = value; a1.setValue(val * 2); b1.setValue(val * 3); } public int getValue() { return val; } public void dump() { System.out.println(val + “:” + a1.getValue() + “:” + b1.getValue()); } } The Container class has data members a1 and b1, which are instances of class WidgetA and WidgetB, respectively. The Container class constructs the instance of WidgetA, and then uses it as the parameter for constructing an instance of WidgetB. The WidgetB class holds onto the reference to the instance of class WidgetA in data member AA. So there is only one instance of class WidgetAin this example, and it is referenced two times. All three of these classes expose a property named Value. Whenever the Value property of the Container object is changed, it in turns changes the Value property of a1 and b1. The Container class also contains a method called dump() which is used to print out its Value property, along with the Value property of a1 and b1. An object graph for these relationships is shown in Figure 5.3. Figure 5.3. Object relationships It is important that the serialized data for this example include only one instance of class WidgetA. When the objects are deserialized this single instance of class WidgetA is recreated and referenced by the instance of the Container class in its data member a1, and by the instance of class WidgetBin its data member AA. Let’s create an application to illustrate how this works. We create an application called Example5that contains an instance of Container named aContainer. This application will take a command- line parameter, telling it whether to save or restore the state of the data member aContainer. When the command-line parameter is save, the application creates an instance of Container, sets its Value property to 13, and then serializes it to a file named Example5.tmp. When the command-line parameter is restore, the application restores the instance of Container by reading it from file page 76