Sunday, April 17, 2011

What should be done when super class implements the Externalizable interface?

Well, in this case the super class will also have the readExternal and writeExternal methods as in Car class and will persist the respective fields in these methods.

import java.io.*;

/**
 * The superclass implements externalizable
 */
class Automobile implements Externalizable {
    
    /*
     * Instead of making thse members private and adding setter
     * and getter methods, I am just giving default access specifier.
     * You can make them private members and add setters and getters.
     */
    String regNo;
    String mileage;
    
    /* 
     * A public no-arg constructor 
     */
    public Automobile() {}

    Automobile(String rn, String m) {
    regNo = rn;
    mileage = m;
    }

    public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(regNo);
    out.writeObject(mileage);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        regNo = (String)in.readObject();
        mileage = (String)in.readObject();
    }

}

public class Car implements Externalizable {

    String name;
    int year;

    /*
     * mandatory public no-arg constructor
     */
    public Car() { super(); }
    
    Car(String n, int y) {
    name = n;
    year = y;
    }

    /** 
     * Mandatory writeExernal method. 
     */
    public void writeExternal(ObjectOutput out) throws IOException  {
    // first we call the writeExternal of the superclass as to write
    // all the superclass data fields
    super.writeExternal(out);

    //Now the subclass fields
    out.writeObject(name);
    out.writeInt(year);
    }

    /** 
     * Mandatory readExternal method. 
     */
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    // first call the superclass external method
    super.readExternal(in);
    
    //Now the subclass fields
    name = (String) in.readObject();
    year = in.readInt();
    }

    /** 
     * Prints out the fields. used for testing!
     */
    public String toString() {
        return("Reg No: " + regNo + "\n" + "Mileage: " + mileage +
               "Name: " + name + "\n" + "Year: " + year );
    }
}

In this example since the Automobile class stores and restores its fields in its own writeExternal and readExternal methods, you dont need to save/restore the superclass fields in sub class but if you observe closely the writeExternal and readExternal methods of Car class closely, you will find that you still need to first call the super.xxxx() methods that confirms the statement the externalizable object must also coordinate with its supertype to save and restore its state.

No comments:

Post a Comment

Chitika