We have a super class called "Vehicle", that implements the marker interface Serializable. Then we have a child class called "Car", that inherits "Vehicle", thus the child class "Car" also implements the Serializable marker interface, because of it's parent "Vehicle".
Now we can Serialize any instance of a Vehicle to a File, without any problems. But when we try to perform Deserialization of that File, to an Object of type "Car", then the program throws an Exception.
The way I solved this is by implementing the Serializable marker interface manually in the "Car" class.
Why is that the case? From all things I read on Serialization today, nobody seems to cover this issue.
The conclusion I came to is the following: When the "Car" class inherits the "Vehicle" class, it also inherits the interface implemented in "Vehicle", thus the "Car" object is serializable, but once we serialize an instance of the "Car" object to a File (for example: "car1.ser"), the "car1.ser" file has an object written to it, with all of it's modifiers, attributes, methods and etc. But somehow the object of type "Car", that is written to the "car1.ser" file, does not inherit the "Serializable" marker from it's parent. What is the reason for that, I am not really sure.
CodePudding user response:
What exception? (please consider to add it to the post, since it seems like an "important detail")
Sorry, cannot re-produce/comprehend:
package com.example.serial;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerialTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Car car = new Car();
car.manufacturer = "Toyota";
car.model = "Land Cruiser";
// tmp memory:
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// write object:
ObjectOutputStream oos = new ObjectOutputStream(outStream);
oos.writeObject(car);
// input stream of "tmp memory":
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
// read object:
ObjectInputStream ois = new ObjectInputStream(inStream);
Car c2 = (Car) ois.readObject();
// print/verify:
System.out.println(c2);
}
}
class Vehicle implements Serializable {
private static final long serialVersionUID = 0L;
String manufacturer;
}
class Car extends Vehicle {
String model;
}
Prints:
com.example.serial.Car@1ed6993a
We can also do:
Vehicle car = new Car();
// ... same code, but without "model"
But not:
Vehicle car = new Vehicle();
...
..this will lead to:
java.lang.ClassCastException: class com.example.serial.Vehicle cannot be cast to class com.example.serial.Car
at this line:
Car c2 = (Car) ois.readObject();
Reference: https://docs.oracle.com/en/java/javase/17/docs/specs/serialization/serial-arch.html
