How does the below code work?
class A {
int a = 10;
}
class B extends A implements Serializable{
}
public class Test {
public static void main(String[] args){
B obj = new B();
obj.a = 25;
//Code to serialize object B (B b= new B()),
// deserialize it and print the value of 'a'.
}
}
The code prints 10 even though I have changed the value of ‘a’ in the code.
Any explanation for this behaviour ?
The default value of
ais 10 – it will be set to 10 when the object is created. If you want to have a realistic test, set it to a different value after instantiation and then serialize it.As for your update – if a class is not serializable, its fields are not serialized and deserialized. Only the fields of the serializable subclasses.