关于这道SCJP题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 implement

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/30 10:48:14
关于这道SCJP题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(

关于这道SCJP题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 implement
关于这道SCJP题
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.
Answer: D
请问,我认为选C,难道是我理解错了,答案给的是选D.

关于这道SCJP题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 implement
选D.
这道题是考序列化得知识:
首先,要清楚,为什么要序列化,序列化和反序列是为了在保存类的实例的时候,还可以将它原封不动的还原回来.比如:我们将Banan2的实例保存到文件当中,如果还想再从文件中读出Banana2的实例对象,就得实现序列化接口.
在对对象序列化的时候,没有什么特别的,就是在这反序列化的时候,得先执行一下基类的构造,(前提是父类没有实现序列化接口,如果父类实现了序列化接口的话,就不会执行父类的构造了)为什么呢?这就得用多态来解释了,
这就好比我们用多态来定义一个对象一样,java的反序列化也是这么干的.
Food banana = new Banana2();
这样解释不知道你懂了没有,我说的也不准确,只能这样了.