Junior — Middle
What does the Serializable class do in Java and why is it rarely used in practice?
sobes.tech AI
Answer from AI
In Java, the Serializable interface is used to indicate that objects of a class can be serialized — that is, converted into a byte stream for storage or transmission.
Why it is rarely used in practice:
- Default serialization can be unsafe and inefficient.
- Maintaining class version compatibility (serialVersionUID) is required; otherwise, deserialization may fail after class changes.
- More modern and flexible serialization methods are often used, such as JSON, XML, or buffer protocols (protobuf).
- Java object serialization can lead to performance and security issues.
Example:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
// getters and setters
}
Thus, Serializable is a simple serialization method, but in real projects, other approaches are often preferred due to limitations and risks.