2 Replies Latest reply: May 12, 2010 7:08 PM by 843790 RSS

    ObjectStream

    843790
      Question. Why is the output of the Car object different at two points within (line 7 & 30) the program ?
      1  import java.io.*;
      2          public class CodeWalkSeven {
      3   
      4    public static void main(String []arg){
      5        
      6        Car cars = new Car("Nissan",1500,"Brown");
      7        System.out.println("before: "+cars.make+" "+cars.weight);
      8        
      9        try{
      10            FileOutputStream out = new FileOutputStream(".//src//Chpt8//"+
      11                    "UnderstandStreams//Car.ser");
      12           ObjectOutputStream os = new ObjectOutputStream(out);
      13            os.writeObject(cars);
      14           os.close();
      15        }catch(IOException e){
      16            e.printStackTrace();
      17        }
      18
      19
      20        try{
      21            FileInputStream in = new FileInputStream(".//src//Chpt8//UnderstandStreams//"+
      22                    "Car.ser");
      23            ObjectInputStream oi = new ObjectInputStream(in);
      24            cars =  (Car)oi.readObject();
      25            oi.close();
      26        }catch(Exception e){
      27            e.printStackTrace();
      28        }
      29        
      30            System.out.println("after: "+cars.make+" "+cars.weight);
      31         }
      32     }
      33
      34       class NonLiving {}
      35
      36     class Vehicle extends NonLiving{
      37           String make = "Lexus";
      38            String color = "Brown";
      39           }
      40
      41          class Car extends Vehicle implements Serializable{
      42                  protected int weight = 1000;
      43
      44          Car(String make,int weight,String color){
      45                 this.make = make;
      46                 this.weight = weight;
      47                 this.color = color;
      48
      49              }
      50          }