2

I have read Constructor Calls while serialization , Serialization Rules but can't able to find out all rule for member variable.

I have below question:

Student.java

class Person {
}
class Student extends Person implements Serialization {
   List<Book> books; 
   Student(){}
   Student(List<Book> books) {
      this.books = books;
   }
}

class Book implements Serialization {
  Book() {}
  String bookId;
  Book(String bookId) {
      this.bookId = bookId;
  }

}

Here Student is serializable and Book class is also serializable then what are rules for constructor calling serializable and deserializable.

  1. Is required default constructor in Book class? If Yes , Then Why required default constructor while deserialization.
  2. How constructor calls while serialization and deserialization?
Community
  • 1
  • 1
Kamlesh Kanazariya
  • 1,209
  • 2
  • 15
  • 32

2 Answers2

0

See my answers below:

Is required default constructor in Book class?

-> Yes it is mandatory or else serialization will fail.

How constructor calls while serialization and deserialization?

-> Serialization uses reflection and a default constructor is mandatory to use reflection.

Lokesh
  • 7,810
  • 6
  • 48
  • 78
  • As per my knowledge I know that default constructor is not required in Student class because it implement serialization and Default Constructor is only required in super class as does not implement serialization Now Why default constructor is required in Book class as it already implements serialization. – Kamlesh Kanazariya Apr 21 '16 at 05:35
  • Where is Super class here? Are you talking about Object class? – Lokesh Apr 21 '16 at 05:37
  • I am trying to understand when default constructor is required while deserialization. As per my knowledge Default constructor is only required when class does not implement serialization. – Kamlesh Kanazariya Apr 21 '16 at 05:39
  • Whats the source of this info -> "As per my knowledge Default constructor is only required when class does not implement serialization." If you are using inheritance then parent class must have default constructor but there is no parent class here. – Lokesh Apr 21 '16 at 05:41
  • Does not same rule is applied for member reference which applied in super class? Assume that There is Person super class of student. – Kamlesh Kanazariya Apr 21 '16 at 05:51
0

Actually, you should put a no-arg constructor in the class of Person which is the superclass of Student.

If don't, a java.io.InvalidClassException in runtime will be thrown when deserialization.

Tangoo
  • 1,329
  • 4
  • 14
  • 34