Reputation: 10598
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 ?
Upvotes: 10
Views: 10882
Reputation: 4982
If you are a serializable class, but your superclass is NOT serializable, then any instance variables you INHERIT from that superclass will be reset to the values they were given during the original construction of the object. This is because the non- serializable class constructor WILL run! In fact, every constructor ABOVE the first non-serializable class constructor will also run, no matter what, because once the first super constructor is invoked, (during deserialization), it of course invokes its super constructor and so on up the inheritance tree.
Upvotes: 1
Reputation: 21
If class B extends class A, and A is not serializable, then all the instance variables of class A are initialized with their default values (which is 10 in this case) after de-serialization of class B.
Upvotes: 2
Reputation: 62583
Since B
extends A
, it is an A
. This means that b instanceof Serializable
returns true
.
So, as long as the object you try to serialize returns true for the instanceof Serializable
checks, you can serialize it. This applies for any composite objects contained within this object itself.
But you can't do A a = new A();
and attempt to serialize a
.
Consider this:
java.lang.Object
doesn't implement Serializable
. So, no one would've been able to serialize any objects in Java in that case! However, that's not the case at all. Also, in projects where there are multiple JavaBeans involved that extend a common super type, the general practice is to make this super type implement Serializable
so that all the sub classes don't have to do that.
Upvotes: 7
Reputation: 597076
The default value of a
is 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.
Upvotes: 11
Reputation: 533500
If a parent class is not serializable its fields are initialised each time the object is deserialized. i.e. The object still needs to be constructed.
Upvotes: 0