0

The height in Stu class is static. It should be 0. But it outputs 180. Can anyone tell me what's wrong? Thank you so much!

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class SerializableDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { w(); r(); } private static void r() throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream(new FileInputStream( "d:/abc/stu")); Stu stu = (Stu) in.readObject(); System.out.println(stu); in.close(); } private static void w() throws IOException { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( "d:/abc/stu")); out.writeObject(new Stu(1, "z3", "m", 20, 180, 80)); out.close(); } } class Stu implements Serializable { private static final long serialVersionUID = 2016L; private int id; private String name; private String gender; private int age; private static int height; private transient int weight; public Stu(int id, String name, String gender, int age, int height, int weight) { this.id = id; this.name = name; this.gender = gender; this.age = age; this.height = height; this.weight = weight; } @Override public String toString() { return "Stu [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + ", height=" + height + ", weight=" + weight + "]"; } }

28th Jul 2016, 4:08 PM
Chaie Li
Chaie Li - avatar
4 ответов
+ 1
Looks like in method w() when you create the object, youre passing 180 into the height argument.
29th Jul 2016, 12:50 AM
James
James - avatar
+ 1
Nevermind I get what you're saying. So, static variables can't be serialized. Doesn't work. What happens when you run the program with both w, and r methods is 180 because the static variable is attached to the class and any instances of it. Even if it's not being serialized, it's still in memory from the program, and when the file gets deserialized, it will will apply to that instance because static applies itself to all instances of the class after being called. Now when you remove the w() to just read the serialized code, you are not setting the static variable so when you deserialize the file, the static variable will be default 0 because it was never serialized with the rest. Hope I explained that well enough.
29th Jul 2016, 1:26 PM
James
James - avatar
0
But when I run w() and r() separated. It outputs 0.
29th Jul 2016, 12:02 PM
Chaie Li
Chaie Li - avatar
0
Got it, thanks!
30th Jul 2016, 6:38 AM
Chaie Li
Chaie Li - avatar