About Question enthuware.ocpjp.v7.2.1702 :
Posted: Mon Mar 24, 2014 5:38 pm
I don´t understand why the JVM cares about the missing no-arg constructor I thougt that at deserialization, no constructor will be called?
Java Certification Resources and Java Discussion Forum
https://www.enthuware.com/forum/
For serializable objects, the no-arg constructor for the first non-serializable supertype is run. For serializable classes, the fields are initialized to the default value appropriate for its type. Then the fields of each class are restored by calling class-specific readObject methods, or if these are not defined, by calling the defaultReadObject method. Note that field initializers and constructors are not executed for serializable classes during deserialization.
Code: Select all
What will be a part of the output when the following code is compiled and run?
class Boo {
int boo = 10;
public Boo(int k){ System.out.println("In Boo k = "+k); boo = k;}
}
class BooBoo extends Boo {
public BooBoo(int k ){ super(k); System.out.println("In BooBoo k = "+k); }
}
class Moo extends BooBoo implements Serializable {
int moo = 10;
public Moo(){ super(5); System.out.println("In Moo"); }
}
public class TestClass {
public static void main(String[] args) throws Exception{
var moo = new Moo();
var fos = new FileOutputStream("c:\\temp\\moo1.ser");
var os = new ObjectOutputStream(fos);
os.writeObject(moo);
os.close();
var fis = new FileInputStream("c:\\temp\\moo1.ser");
var is = new ObjectInputStream(fis);
moo = (Moo) is.readObject();
is.close();
}
}
Code: Select all
1. In Boo k = 5
In BooBoo k = 5
2. In Boo k = 0
In BooBoo k = 0
3. In Moo
4. It will throw an exception at runtime.
5. It will not compile.
Code: Select all
While instantiating a new Moo, all the constructors will be executed. So it will print
In Boo k = 5
In BooBoo k = 5
In Moo
There will not be any problem while serializing the Moo object.
However, while deserializing, the JVM will not find any no-arg constructor that can be invoked to initialize BooBoo.
No-args constructor is required in BooBoo because BooBoo is the most specific class in the class hierarchy that doesn't implement Serializable.
So it will throw an InvalidClassException.
Code: Select all
var moo = new Moo()
Code: Select all
In Boo k = 10
In BooBoo k = 5