Assuming that the serializeBanana2() and the deserializeBanana2()
methods will correctly use Java serialization and given:
13. import java.io.*;
14. class Food {Food() { System.out.print(”1”); } }
15. class Fruit extends Food implements Serializable {
16. Fruit() { System.out.print(”2”); } }
17. public class Banana2 extends Fruit { int size = 42;
18. public static void main(String [] args) {
19. Banana2 b = new Banana2();
20. b.serializeBanana2(b); // assume correct serialization
21. b = b.deserializeBanana2(b); // assume correct
22. System.out.println(” restored “+ b.size + “ “); }
23. // more Banana2 methods
24. }
What is the result?
A. Compilation fails.
B. 1 restored 42
C. 12 restored 42
D. 121 restored 42
E. 1212 restored 42
F. An exception is thrown at runtime.
我想选择C,但答案是D。
------解决方案--------------------------------------------------------
解释:
首先是Banana2 b = new Banana2(); 会调用构造函数,先调用food基类,输出1,再调用fruit基类输出2
然后初始化size变量为42,,然后序列化
接下来反序列化,反序列化的规则是:如果基类全部实现了serializable接口,则不会调用基类的构造函数,如果基类没有实现,则会调用基类的构造函数
则:Food没实现Serializable接口,则要调用它的构造函数,输入1
接下来输入resroted 42
------解决方案--------------------------------------------------------
楼上正解
这里有一个前提需要注意,因为banana2的父类(Fruit)是可序列化的,所以banana2也是可序列化的
因此何以被序列化。