gpt4 book ai didi

java - 为什么在序列化/反序列化的情况下只创建一个父对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:49 24 4
gpt4 key购买 nike

为什么在序列化/反序列化的情况下只创建一个父对象

//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's 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's 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's 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();
}
}
}

输出

B.B()
i = 10
j = 20
Object has been serialized

A's class constructor called
HasCode of A:1311053135 | HasCode of B:1705736037
i = 50
j = 20
A's class constructor called
HasCode of A:1311053135 | HasCode of B:455659002
i = 50
j = 20
A's class constructor called
HasCode of A:1311053135 | HasCode of B:250421012
i = 50
j = 20

虽然多次反序列化 B 的对象,但只创建了 A 类父对象的一个​​对象。为什么只创建一个对象?

最佳答案

您不是在调用 A 的实例的 hashCode() 方法,而是在类 A 中,有 - 在大多数情况下情况 - 只有一个类对象的实例。

让我们分解一下:

b2               // instance of B
.getClass() // Class<B>
.getSuperclass() // Class<A>
.hashCode() // hash code of Class<A>

甚至不可能为 B 实例的“A 部分”获取单独的哈希码:只有一个对象,并且它有只有一个哈希码。

当您创建一个B 时,只会创建一个对象,而不是像您想象的那样创建两个。此对象包含所有 B,其中包括 A 的部分。

关于java - 为什么在序列化/反序列化的情况下只创建一个父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com