Developing Java Beans // the decrement button protected

Developing Java Beans The Java object serialization mechanism requests that an object read or write its own state. In order to handle these requests an object must implement either the java.io.Serializable interface or the java.io.Externalizable interface. 5.2 The java.io.Serializable Interface Objects that implement the java.io.Serializable interface can have their state saved and restored. This state includes data from all of the classes in the object’s class hierarchy. So an object need not worry about the serialization of data from superclasses, as this is handled automatically. The Serializable interface has no methods. It is used as a marker, indicating that the class is serializable. All subclasses of a class that implements this interface will also be serializable. So it is not necessary to declare that a class implements java.io.Serializable if one of its superclasses has already done so. The object serialization mechanism analyzes objects that implement java.io.Serializable, looking for data members to save or restore. By default, all non-static and non-transient data members will be serialized. Let’s take a look at a simple example. We create an applet that contains a single instance of java.awt.Button, which is serializable. The button’s Label property is set by specifying it as a parameter of the constructor. In this case the string Beans Book is used. We also set the button’s Font property, using a bold 36-point font. After adding the button to the applet, we serialize the button to file Saver.tmp. Figure 5.2 shows the applet, and its code is shown here: import java.applet.*; import java.awt.*; import java.io.*; public class SimpleSaver extends Applet { public void init() { Button b = new Button(”Beans Book”); b.setFont(new Font(”System”, Font.BOLD, 36)); add(b); try { FileOutputStream f = new FileOutputStream(”Saver.tmp”); ObjectOutput s = new ObjectOutputStream(f); s.writeObject(b); s.flush(); } catch (Exception e) { System.out.println(e); } } } Figure 5.2. An applet that saves and restores itself page 72
Note: If you are looking for good and high quality web space to host and run your java application check Vision java hosting services

Comments are closed.