Can a class be serialized if one of its member fields is not serializable?

Yes, a class can be serialized even if one of its member fields is not serializable, but special handling is required. If a non-serializable field is included in a serializable class, it must be marked as transient. Otherwise, Java will throw a NotSerializableException during serialization.

Key Points: • A class must implement Serializable to support serialization. • All non-transient member fields should also be serializable. • Non-serializable fields must be declared as transient. • If a non-serializable field is not marked transient, serialization fails with NotSerializableException. • Transient fields are skipped during serialization and restored with default values after deserialization.

Example: Suppose an Employee object contains an Address object. If Address does not implement Serializable, serialization of Employee will fail unless the Address field is marked as transient.

Code Example:

import java.io.Serializable;

class Address {

    private String city;
}

class Employee implements Serializable {

    private int id;
    private String name;

    private transient Address address;
}

In this example:

• Employee is serializable. • Address is not serializable. • The address field is marked transient, so serialization succeeds.

What Happens Without transient?

class Employee implements Serializable {

    private int id;
    private String name;

    private Address address;
}

Attempting to serialize an Employee object will result in:

java.io.NotSerializableException: Address

After Deserialization:

If a transient object reference is skipped during serialization, its value becomes:

null

Example:

Before Serialization:

id = 101 name = "Amol" address = Address Object

After Deserialization:

id = 101 name = "Amol" address = null

Alternative Solution:

Instead of marking the field as transient, the referenced class can also implement Serializable.

class Address implements Serializable {

    private String city;
}

This allows the entire object graph to be serialized.

Interview Tip: A concise interview answer is:

"Yes, a class can be serialized even if one of its fields is not serializable. However, the non-serializable field must be marked as transient. Otherwise, Java throws a NotSerializableException during serialization. Another option is to make the referenced class implement Serializable."