Explain the difference between `Serializable` and `Parcelable` in Android.

Instruction: Discuss the scenarios in which you would use `Serializable` vs. `Parcelable` for object serialization.

Context: This question assesses the candidate's understanding of Android's mechanisms for object serialization and their ability to choose the optimal approach for performance and implementation.

Updated

Official answer

Serializable is Java's marker interface for its object-serialization mechanism; the object graph must be compatible with that mechanism. Parcelable is Android's explicit representation for transferring supported values through Parcel-based APIs, such as small Intent/Bundle data.

A manual Parcelable writes fields in writeToParcel and supplies a Parcelable.Creator that reads them in a matching order. createFromParcel belongs to the Creator, not to the Parcelable instance. In Kotlin, the Parcelize compiler plugin can generate much of this code for supported classes.

Parcelable is designed for Android IPC and is often a suitable choice for Android component arguments. Measure real payloads before promising a speedup over Serializable; implementation and object shape matter. Neither mechanism justifies sending large graphs or full images through a Bundle. Prefer a stable record ID or a suitably permissioned content URI and load the data at the destination.

Do not store marshalled Parcel bytes as a durable file format: the representation is not guaranteed to remain readable across platform changes. Use a versioned durable format/database for long-term storage. Validate data crossing trust boundaries, and do not deserialize arbitrary untrusted Java object streams.

For example, pass a book ID to a detail screen and reload the current book. If a small immutable argument object is useful, Parcelable/Parcelize can express it. Test null/optional fields and round-trip behavior on the supported versions.

Parcel contract, Parcelize

Related Questions