Question 101
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.
答案是D自己想不通,渴望看到详细些的解释^_^
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.
答案是D自己想不通,渴望看到详细些的解释^_^
这道题目出的很微妙,的确没有实现serializeBanana2()和deserializeBanana2(b)
但是你的Banana2类间接继承Food类,而Food类是非序列化类
因此当你deserializeBanana2(b)的时候,Food类其实是初始化的,Fruit类是序列化类不会初始化...
所以是 121 restored 42 这题其实考察你的序列化在继承关系上的使用...具体参考一下其他参考类书籍,我这里说的没有书上详细
将会被原始的构造方法实例化时重新赋值,这就是未序列化的类的构造方法会被运行的原因.
转自 链接:http://www.itzhe.cn/news/20080305/101849_2.html