Why only one parent is created in case of serialization / deserialization
Why only one parent is created in serialization / deserialization case
//superclass A
//A class doesn't implement Serializable
//interface.
class A
{
int i;
// parameterized constructor
public A(int i)
{
this.i = i;
}
// default constructor
public A()
{
i = 50;
System.out.println("A class constructor called");
}
}
// subclass B implementing Serializable interface
class B extends A implements Serializable
{
int j;
public B(int i, int j)
{
super(i);
System.out.println("B.B()");
this.j = j;
}
}
// Driver class
public class SerializationWithInheritanceExample
{
public static void main(String[] args) throws Exception
{
B b1 = new B(10, 20);
System.out.println("i = " + b1.i);
System.out.println("j = " + b1.j);
// Serializing B's(subclass) object
try (FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
// Method for serialization of B class object
oos.writeObject(b1);
}
System.out.println("Object has been serialized\n");
// Reading the object from a file
readObject();
readObject();
readObject();
}
static void readObject()
{
// Reading the object from a file
try (FileInputStream fis = new FileInputStream("abc.ser"); ObjectInputStream ois = new ObjectInputStream(fis))
{
// Method for de-serialization of B class object
B b2 = (B) ois.readObject();
System.out.println("HasCode of A:"+ b2.getClass().getSuperclass().hashCode() +" | HasCode of B:"+b2.hashCode());
System.out.println("i = " + b2.i);
System.out.println("j = " + b2.j);
} catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Output
B.B() i = 10 j = 20 Object has been serialized A class constructor called HasCode of A:1311053135 | HasCode of B:1705736037 i = 50 j = 20 A class constructor called HasCode of A:1311053135 | HasCode of B:455659002 i = 50 j = 20 A class constructor called HasCode of A:1311053135 | HasCode of B:250421012 i = 50 j = 20
During de-serialization of object B, only one object of the parent class is created multiple times. Why is only one object being created?
source to share
You don't call an hashCode()
instance method A
, but a class A
, in most cases only one instance of a class object.
Let's break it down:
b2 // instance of B
.getClass() // Class<B>
.getSuperclass() // Class<A>
.hashCode() // hash code of Class<A>
There is no way to get a separate hash for the "parts A
" of an instance B
: there is only one object and it has only one hash.
When you create B
, only one object is created, not two as you seem to think. This object contains everything B
, which includes parts A
.
source to share
In case A you get the hashcode of class A. In case B you get the hashcode of instance B. And your 3 instances of B share 1 superclass A (along with class B). So, for example, if you call b2.getClass().hashcode()
3 times, then the result will be equal for all these method calls, because you have 1 class B.
source to share