Then in this case, you need to persist the super class fields also in the sub class that implements Externalizable interface. Look at this example.
/**
* The superclass does not implement externalizable
*/
class Automobile {
/*
* 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 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 {
/*
* Since the superclass does not implement the Serializable interface
* we explicitly do the saving.
*/
out.writeObject(regNo);
out.writeObject(mileage);
//Now the subclass fields
out.writeObject(name);
out.writeInt(year);
}
/**
* Mandatory readExternal method.
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
/*
* Since the superclass does not implement the Serializable interface
* we explicitly do the restoring
*/
regNo = (String) in.readObject();
mileage = (String) in.readObject();
//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 );
}
}
Here the Automobile class does not implement Externalizable interface. So to persist the fields in the automobile class the writeExternal and readExternal methods of Car class are modified to save/restore the super class fields first and then the sub class fields.
No comments:
Post a Comment