gpt4 book ai didi

java - 序列化和继承

转载 作者:行者123 更新时间:2023-11-30 04:36:40 25 4
gpt4 key购买 nike

以下问题(Sierra Bates SCJP 指南)的答案是 pcp:

import java.io.*;

class Player {
Player() { System.out.print("p"); }
}

class CardPlayer extends Player implements Serializable {
CardPlayer() { System.out.print("c"); }

public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();

try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();

FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}

因此它得到 pcp:

"pc" is printed as the serialized state of Cardplayer - the inherited p and Cardplayer's c. The third p in the output is the result of the superclass Player constructor running - as it's not serializable - printing p.

答案就是这样得出的不是吗?

最佳答案

答案是肯定的。

Java doc of Serializable

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime

关于java - 序列化和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333895/

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