FileDocCategorySizeDatePackage
Example5.javaAPI DocExample2362Tue Jun 03 23:36:14 BST 1997None

Example5.java

// This example is from the book Developing Java Beans by Robert Englander. 
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

// Chapter 5 -- The Example5 class and associated classes

import java.io.*;

class WidgetA implements Serializable
{
   protected int val;
   
   public WidgetA()
   {
   }

   public void setValue(int value)
   {
      val = value;
   }

   public int getValue()
   {
      return val;
   }
}

class WidgetB implements Serializable
{
   protected int val;
   protected WidgetA AA;

   public WidgetB(WidgetA a)
   {
      AA = a;
   }

   public void setValue(int value)
   {
      val = value;
   }

   public int getValue()
   {
      return val;
   }
}

class Container implements Serializable
{
   protected int val;
   protected WidgetA a1;
   protected WidgetB b1;

   public Container()
   {
      a1 = new WidgetA();
      b1 = new WidgetB(a1);
   }

   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());
   }
}

public class Example5
{
   // the application entry point
   public static void main(String[] args)
   {
      if (args[0].equals("save"))
      {
         Container c = new Container();
         c.setValue(13);
         try
         {
            FileOutputStream f = new FileOutputStream("Example5.tmp");
            ObjectOutputStream s = new ObjectOutputStream(f);
            s.writeObject(c);
            s.flush();
         }
         catch (Exception e)
         {
            System.out.println(e);
         }

         c.dump();
     }
     else if (args[0].equals("restore"))
     {
        try
        {
           FileInputStream f = new FileInputStream("Example5.tmp");
           ObjectInputStream s = new ObjectInputStream(f);
           Container c = (Container)s.readObject();
           c.dump(); 
        }
        catch (Exception e)
        {
           System.out.println(e);
        }
     }
   }
}