SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2004
    Location
    India
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Serializable interface

    import java.io.*;

    class SuperNotSerial {
    public static void main(String [] args) {
    Dog d = new Dog(35, "Fido");
    System.out.println("before: " + d.name + " " + d.weight);
    try {
    FileOutputStream fs = new FileOutputStream("testSer.ser");
    ObjectOutputStream os = new ObjectOutputStream(fs);
    os.writeObject(d);
    os.close();
    } catch (Exception e) { e.printStackTrace(); }
    try {
    FileInputStream fis = new FileInputStream("testSer.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    d = (Dog) ois.readObject();
    ois.close();
    } catch (Exception e) { e.printStackTrace(); }
    System.out.println("after: " + d.name + " " + d.weight);
    }
    }
    class Dog extends Animal implements Serializable{
    String name;
    Dog(int w, String n) {
    weight = w; // inherited
    name = n; // not inherited
    }
    }
    class Animal { // not serializable !
    int weight = 42;
    }


    Please make me understand if instead of class Dog, class Animal implements Serializable, what would be result and why?

  2. #2
    SitePoint Addict mmanders's Avatar
    Join Date
    Jul 2006
    Location
    Edinburgh, Scotland
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm afraid I don't understand what you are asking, could you give some more details please? Also, could you enclose your code in code tags to make it more readable?

  3. #3
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In this case there would be no difference. This is an issue of OOP. So you have:

    Code:
     class Animal {
     ...
     }
     
     class Dog extends Animal {
     ...
     }
    with this:
    Code:
     class Dog extends Animal implements Serializable {
      ...
      }
     class Cat extends Animal {
       ...
       }
    Now only Dog implements Serializable

    with this:
    Code:
     class Animal implements Serializable {
      ...
      }
      
      class Dog extends Animal {
      ...
      }
     
      class Cat extends Animal {
       ...
       }
    In this case both Dog and Cat implement Serializalbe since the superclass Animal implements Serializable. This is typically how you want to arrange things.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •