简体   繁体   中英

Java Serialization for Extended Class

In java serialization class Mp3player extends ElectronicDevice implements Serializable in this code super class electronicdevice is not implemented serializable. here super class is also getting serialized. my understanding is super class is also gets serialized due to extends.let me know my understanding is correct or not.

 import java.io.*;
 class ElectronicDevice { 
      ElectronicDevice() 
      {
           System.out.print("ed "); 
      }
  }
 class Mp3player extends ElectronicDevice implements Serializable {
       Mp3player() 
       { 
          System.out.print("mp "); 
       }
 }
class MiniPlayer extends Mp3player {
     MiniPlayer()
     { 
         System.out.print("mini "); 
     }
     public static void main(String[] args) {
          MiniPlayer m = new MiniPlayer();
          try {
                 FileOutputStream fos = new FileOutputStream("dev.txt");
             ObjectOutputStream os = new ObjectOutputStream(fos);
                 os.writeObject(m); os.close();

                 FileInputStream fis = new FileInputStream("dev.txt");
                 ObjectInputStream is = new ObjectInputStream(fis);
                 MiniPlayer m2 = (MiniPlayer) is.readObject(); 
                 is.close();
                 System.out.println();
          } catch (Exception x) {
                System.out.print("x "); 
          }
     }
  }

No.During the process of serialization only the fields of Serializable objects are written out and restored.

According to javadocs

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class.

Where as the fields of serializable subclasses will be restored from the stream.

Please look into this example
Here ElectronicDevice is not Serializable ,where as Mp3player is Serializable .Observe the fields of respected classes behaviour in serialization process.

import java.io.*;
class ElectronicDevice  { 
  public int i = 0;
  protected ElectronicDevice() 
  {
       System.out.println("ed "); 
  }
}
class Mp3player extends ElectronicDevice implements Serializable {
   int j =0;
   Mp3player() 
   { 
       System.out.println("mp "); 
   }
}
class MiniPlayer extends Mp3player {
  MiniPlayer()
  { 
      System.out.println("mini "); 
  }
 public static void main(String[] args) {
      MiniPlayer m = new MiniPlayer();
      m.i = 30;
      m.j = 40;
      try {
             System.out.println("i value before serialization: "+m.i);//prints 30
             System.out.println("i value before serialization: "+m.j);//prints 40
             FileOutputStream fos = new FileOutputStream("dev.txt");
             ObjectOutputStream os = new ObjectOutputStream(fos);
             os.writeObject(m); os.close();

             FileInputStream fis = new FileInputStream("dev.txt");
             ObjectInputStream is = new ObjectInputStream(fis);
             MiniPlayer m2 = (MiniPlayer) is.readObject(); 
             is.close();
             System.out.println("i value after serialization: "+m2.i);//prints o
             System.out.println("j value after serialization: "+m2.j);//prints 40
             System.out.println();
        } catch (Exception x) {
            x.printStackTrace();
            System.out.print("x "); 
       }
   }
 }

Since super class doesn't implement Serializable contents of the super class wont get serialized. Only the contents of the subclass would get serialized. When you deserialize the default constructor of the superclass would get executed and the fields of the superclass initialized as if you invoked the default constructor.

Following example illustrates this.

public class SerializationTest {

    public static class Base {
        private String name;

        public Base() {
            this.name = "johnDow";
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class Sub extends Base implements Serializable {
        private static final long serialVersionUID = 1L;
        private String age;

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }
    }

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteArrayOS);
        Sub s = new Sub();
        s.setName("name");
        s.setAge("10");
        out.writeObject(s);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArrayOS.toByteArray()));
        Sub d = (Sub) ois.readObject();
        System.out.println(d.getName() + "-" + d.getAge());
    }
}

What gets printed is

johnDow-10

This is the rule for superclass serialization:

If you are a serializable class, but your superclass is NOT serializable, then any instance variables you INHERIT from that superclass will be reset to the values they were given during the original construction of the object. This is because the nonserializable class constructor WILL run.

Therefore, if you add some instance variables to ElectronicDevice, be aware that the superclass 's state will be not serialized. (unless the superclass implements Serializable)

my understanding is super class is also gets serialized due to extends.let me know my understanding is correct or not.

The short answer is NO .

In java, every class is a subclass of Object . Does Object itself implement Serializable ?

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields”

Reference - http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM