public class Parent {
public Parent() {
System.out.println("Parent");
}
}
public class Child extends Parent implements Serializable {
public Child() {
System.out.println("Child");
}
}
public class Demote {
public static void main(String[] args) {
Child c=new Child();
try {
FileOutputStream fos=new FileOutputStream
("D:\\DemoFile\\Testword5.txt");
ObjectOutputStream oot=new ObjectOutputStream(fos);
oot.writeObject(c);
FileInputStream fin=new FileInputStream
("D:\\DemoFile\\Testword5.txt");
ObjectInputStream oin=new ObjectInputStream(fin);
oin.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output of this code is - Parent Child Parent.
The first set Parent Child is called because zero argument constructor is called. oin.readObject() is returning a child object . Then why only parent class's constructor is called and why not the child class
No, it's fine to have a parent class without the default constructor as long as its children don't invoke super() .
We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".
If parent class implements a constructor with arguments and has no a constructor with no arguments, then the child constructors must explicitly call a parents constructor.
Remember we mentioned that the parent class constructor is called first when an object is created? That's why super() should always be first in a constructor!
The Parent constructor is called because it doesn't implement Serializable. The Child however does implement Serializable to it is not called.
Quoting from The Java Docs for Serializable:
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
The Serializable classes themselves do not need a no-args constructor, and it will not be used for initializing them if it exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With