Java Serialization readObject Access Modifier
Given the Product class: and the Shop class: What is the result? -
- 
Community Votes
100% of anonymous learners picked answer B. Votes are pick records left by other test-takers — they are not the verified answer.
Community Insight
Tests knowledge that the deserialization hook must be private; if public, it is ignored and transient variables retain their initial defaults.
Determines the output of a Java program involving serialization when the private readObject method is incorrectly declared as public, causing transient fields to remain default values.
Learners often select C or D, assuming the custom logic runs regardless of visibility, missing the strict contract requirements of the Serialization API.
Community Discussion (4 comments)
Comments & Corrections
No comments yet — spotted an error or have a note? Share it below.
Expert Analysis
Why the Answer Is Correct
The correct output is B because thereadObject method in the Product class is declared as public. According to Java's serialization specification, for the custom readObject method to be invoked during deserialization, it must have the signature private void readObject(ObjectInputStream ois). Since it is public, the reflection mechanism does not recognize it as a valid callback. Consequently, the default deserialization process occurs, leaving the transient field price at its default primitive value of 0.0, while the non-transient name is restored.Why the Other Options Are Wrong
Options C and D imply that thereadObject method executed successfully, which is incorrect due to the access modifier violation. Option A is incorrect because the code compiles fine; the error is logical/runtime behavior, not syntax. Option E is incorrect because no exception is thrown; the serialization simply proceeds without invoking the custom logic.Community Comment Notes
Community consensus correctly identifies B. As user SrinivasJasti noted, "Since it is public,loses its special status in the serialization process." User Langton also confirmed that "for readObject method to be called it has to be difined as private which is not the case here."Exam Strategy
Memorize the exact signature for serialization hooks: they must be private. Any deviation in visibility (protected, package-private, public) causes the JVM to ignore them.
Frequently Asked Questions
Can readObject be protected?
No, it must be strictly private to be recognized by the serialization runtime.
What happens to transient fields if readObject is ignored?
They are not restored from the stream and revert to their default initialization values (e.g., 0.0 for double).