【发布时间】:2013-08-24 10:49:30
【问题描述】:
在java序列化类Mp3player扩展ElectronicDevice在这段代码中实现了Serializable超类electronicdevice没有实现可序列化。这里的超类也正在序列化。我的理解是超类也因为扩展而被序列化。让我知道我的理解是否正确。
import java.io.*;
class ElectronicDevice {
ElectronicDevice()
{
System.out.print("ed ");
}
}
class Mp3player extends ElectronicDevice implements Serializable {
Mp3player()
{
System.out.print("mp ");
}
}
class MiniPlayer extends Mp3player {
MiniPlayer()
{
System.out.print("mini ");
}
public static void main(String[] args) {
MiniPlayer m = new MiniPlayer();
try {
FileOutputStream fos = new FileOutputStream("dev.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(m); os.close();
FileInputStream fis = new FileInputStream("dev.txt");
ObjectInputStream is = new ObjectInputStream(fis);
MiniPlayer m2 = (MiniPlayer) is.readObject();
is.close();
System.out.println();
} catch (Exception x) {
System.out.print("x ");
}
}
}
【问题讨论】:
-
代码试图准确显示什么?你不明白它的作用是什么?
-
java 序列化机制只关注实现
Serializable的类的实例,因此在您的情况下,从ElectronicDevice继承的字段(如果有)默认情况下不会被序列化/反序列化,请参阅this回答。 -
在上面的代码中,电子设备没有实现可序列化的接口,但结果(反序列化后)“ed”也出现在输出中。
标签: java