Search code examples
javafunctionserializationcallsignature

wrong parameter passes to a function and it still works (customized serialization)


I have a class which implements Serializable and overrides its functions - writeObject and readObject.

How is it that while calling function readObject() there is no parameter passed but while defining the overridden there is a parameter. Its not even a parameter followed by any number of parameters signature [ like: (int i...)]

How is this code working:

//I understand this part:

package CustomizedSerialization;

import java.io.Serializable;

public class Cat implements Serializable
{
    int k = 30;
    int j = 10;
    char c = 'c';
}


package CustomizedSerialization;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Dog2 implements Serializable 
{

    transient Cat c = new Cat();

    private void writeObject(ObjectOutputStream oos) throws IOException
    {
        int x = c.j;
        oos.writeInt(x);
    }

*********marked line 1a - input parameter of readObject********

    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException
    {
        ois.defaultReadObject();

        c = new Cat();


    }

}

package CustomizedSerialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeDemo2 {

    public static void main(String[] args) throws IOException, ClassNotFoundException 
    {

        Dog2 d = new Dog2();

        System.out.println("Before serialization "+ d.c.j);
        FileOutputStream fos = new FileOutputStream("C:\\serializedFile.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos); 

        oos.writeObject(d);



        System.out.println("After serialization");
        FileInputStream fis = new FileInputStream("C:\\serializedFile.ser");        
        ObjectInputStream ois = new ObjectInputStream(fis); 

*********marked line 1a - input parameter of readObject********

        Dog2 d1 = (Dog2) ois.readObject();

        System.out.println(d1.c.j);
        System.out.println(d1.c.c);
    }

}

How is "line marked 1 a" in programs (Dog2 and SerializeDemo2) working? SerializeDemo2 calls function readObject of class Dog2 without any parameter but while defining the called function (readObject) in class Dog2, it has an input parameter. How is it not throwing error.


Solution

  • ObjectInputStream.readObject() with no parameters calls the deserialized object's readObject(ObjectInputStream ois) method, if it exists, and that in turn should call ObjectInputStream.defaultReadObject(). These are three distinct methods, and none of them is an override of any other.