Reputation: 457
I just started with this topic. My understanding says that , if you want to save instance variables of a class , so that it can be used later... you may use "serializable" interface with no methods defined... But i have a doubt that , what happens in inheritance... Suppose my superclass is not-serialized wheras sub-class is serialized...can i save my superclass instance variables ?? Although, i know this... the costructor of superclass is being called and it will run...but what dat mean? is it mean that , i can't save instance variable of superclass....
In the below program... the created file will store numerical values(43,23) or just variables "height" and "weight"???
import java.io.*;
class A {
String sex;
public void gone(String sex){
this.sex = sex;
System.out.println("i m " + sex);
}
}
public class serialio1 extends A implements Serializable {
int height;
int weight;
public static void main(String[] args){
serialio1 myBox = new serialio1();
myBox.go(43,23);
try{
FileOutputStream fs = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myBox);
os.close();
FileInputStream fileStream = new FileInputStream("foo.ser");
ObjectInputStream ms = new ObjectInputStream(fileStream);
Object one = ms.readObject();
Object two = ms.readObject();
int h = (int) one;
int w = (int) two;
ms.close();
System.out.println("saved values" + h + w);
} catch(Exception ex){
ex.printStackTrace();
}
}
public void go(int height , int weight) {
this.height = height;
this.weight = weight;
System.out.println(" height is " + height);
System.out.println(" weight is " + weight);
}
}
Upvotes: 2
Views: 4675
Reputation: 310957
Suppose my superclass is not-serialized wheras sub-class is serialized...can i save my superclass instance variables?
Yes, but you have to write extra code, as show in Evgeny's answer.
Although, i know this... the costructor of superclass is being called and it will run...but what dat mean? is it mean that , i can't save instance variable of superclass....
I really can't make any sense out of this, but if you're just repeating your earlier question, the answer is the same too.
In the below program... the created file will store numerical values(43,23) or just variables "height" and "weight"???
I can't make any sense of of that either. It is a non-question. It will store the object that you pass to writeObject(),
and that is what you will get back from readObject().
In your case, a serialio1
object, not integers.
Upvotes: 1
Reputation: 136042
If you have access to super class fields from the subclass you can implement custom serialization
class X {
int x;
}
class Y extends X implements java.io.Serializable {
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(x);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
x = in.readInt();
}
}
Upvotes: 1