Giả sử bạn có hai loại cổ phiếu này, Foo và Bar nơi Bar mở rộng Foo và thực hiện Serializable
Java đối tượng serialization và thừa kế
class Foo {
public String name;
public Foo() {
this.name = "Default";
}
public Foo(String name) {
this.name = name;
}
}
class Bar extends Foo implements java.io.Serializable {
public int id;
public Bar(String name, int id) {
super(name);
this.id = id;
}
}
ý rằng Foo không thực hiện Serializable
. Vậy điều gì sẽ xảy ra khi thanh được tuần tự hóa?
public static void main(String[] args) throws Exception {
FileOutputStream fStream=new FileOutputStream("objects.dat");
ObjectOutputStream oStream=new ObjectOutputStream(fStream);
Bar bar=new Bar("myName",21);
oStream.writeObject(bar);
FileInputStream ifstream = new FileInputStream("objects.dat");
ObjectInputStream istream = new ObjectInputStream(ifstream);
Bar bar1 = (Bar) istream.readObject();
System.out.println(bar1.name + " " + bar1.id);
}
nó in "Mặc định 21". Câu hỏi đặt ra là, tại sao hàm dựng mặc định được gọi khi lớp không được tuần tự hóa?
Bạn không thể đột nhiên tạo ra các thể hiện của một lớp vô tội mà không cần gọi hàm tạo của nó, vì vậy đặc tả nối tiếp yêu cầu gọi một hàm tạo của các lớp không nối tiếp./Bạn có thể muốn có một proxy nối tiếp. –