In: Computer Science
1. Consider the following code:
public class Widget implements Serializable
{
private int x;
public void setX( int d ) { x = d; }
public int getX() { return x; }
writeObject( Object o ) { o.writeInt(x); }
}
Which of the following statements is true?
I. The Widget class is not serializable because no constructor is defined.
II. The Widget class is not serializable because the implementation of writeObject() is not needed.
III. The code will not compile because the implementation of writeObject is incorrect.
Answer- III
Explanation-
I. The Widget class is not serializable because no constructor is defined:
Yes it is true that in order for a class to be serializable, the class requires a no argument constructor, but since the class Widget is not extending any parent class, which means that it isn't a child class. But in this case, it is not necessary because, since the class "widget" 's super class, which is "Object" class has a no-argument constructor. Hence it suffices all the needs and therefore this is a Wrong Option. (False)
II. The Widget class is not serializable because the implementation of writeObject() is not needed:
First of all, the writeObject() method is used for writing the byte stream, created by the process of Serialization in a physical location. Yes it is not needed, since we are not using to retrieve the data (bytestream) from any physical location. But it doesn't mean that the class will not become serializable due to this. Hence the class is Serializable. Therefore this is a Wrong Option. (False)
III. The code will not compile because the implementation of writeObject is incorrect:
Yes the code will not compile because the implementation of the writeObject() method is incorrect. There is no return type provided before the method "writeObject()" , generally this should be "void". Therefore this comes under invalid method declaration and hence the code cannot be compiled due to this reason. (True)