Reputation: 323
When going through how marker interfaces are used in Java, I found writeObject method from ObjectOutputStream class. It receives instance of Object as input and do serialization only when given argument is an instance of Serializable.
Why not writeObject method receives instance of Serializable as input instead of Object, so that type check is done during compile time? What is the reason behind making argument type as Object and perform instanceOf check against Serializable?
Upvotes: 1
Views: 169
Reputation: 1753
For serialization to work, Object
needs to be instance of Serializable
. For writing an object, however, you may see that from jdk sources, there are methods of Object
class being called within the writeObject
. A simple e.g. being obj.getClass()
.
So if the writeObject
method were to take Serializable
as input, ultimately for referencing methods like obj.getClass()
, it would have to be cast to Object
anyway.
Upvotes: 0