은 바 푸를 확장하고 푸 Serializable
를 구현하지 않습니다 Serializable
자바 객체 직렬화 및 상속
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;
}
}
공지 사항을 구현하는이 두 클래스, 푸와 바 말해봐. bar가 직렬화되면 어떻게 될까요?
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);
}
"기본값 21"이 인쇄됩니다. 질문은 클래스가 직렬화되지 않을 때 기본 생성자가 호출되는 이유는 무엇입니까?
생성자를 호출하지 않고 무해한 클래스의 인스턴스를 갑자기 만들 수 없으므로 직렬 사양에서 직렬 처리가 불가능한 클래스의 생성자를 호출해야합니다./직렬 프록시를 원할 수도 있습니다. –