What is the result of executing the following code? (Choose all that apply.)
1: import java.io.*; 2: public class Shape {} 3: public class Main implements Serializable { 4: private String name; 5: private transient int age; 6: private Shape tail; 7: /*from w w w . ja v a 2s.c o m*/ 8: public String getName() { return name; } 9: public Shape getShape() { return tail; } 10: public void setName(String name) { this.name = name; } 11: public void setShape(Shape tail) { this.tail = tail; } 12: public int getAge() { return age; } 13: public void setAge(int age) { this.age = age; } 14: 15: public void main(String[] args) { 16: try(InputStream is = new ObjectInputStream( 17: new BufferedInputStream(new FileInputStream("birds.dat")))) { 18: Main bird = is.readObject(); 19: } 20: } 21: }
D, E.
The code does not compile due to a number of issues, so A and F are incorrect.
First off, the readObject()
method is not available to the InputStream class, and since the ObjectInputStream has been upcast to InputStream, the code will not compile due to line 18, so E is correct.
Line 18 will also not compile because the return type of readObject()
is of type Object and must be cast explicitly to Main in order to be assigned to the Main reference.
Furthermore, constructors and methods on lines 16, 17, and 18 throw checked IOException
that must be caught, so D is also correct.
Note that line 18 also throws ClassNotFoundException.
Lines 3 and 5 compile without issue, so B and C are incorrect.
It should be noted that even if the compilation problems were resolved, the code would still throw an exception at runtime since the Main class includes a Shape reference as a member, and the Shape class does not implement Serializable.