Question

import java.io.*;

public class SuperNotSerial {
public static void main(String[] args) {
    Dog d = new Dog(35, "Fido");
    System.out.println("before: " + d.name + " " + d.weight);
    try {
        FileOutputStream fs = new FileOutputStream("testSer.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(d);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        FileInputStream fis = new FileInputStream("testSer.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        d = (Dog) ois.readObject();
        ois.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("after: " + d.name + " " + d.weight);
}
}

class Dog extends Animal implements Serializable {
String name;

Dog(int w, String n) {
    weight = w; // inherited
    name = n; // not inherited
}
}

class Animal { // not serializable !
int weight = 42;
}

the error which is coming is.

This error is compilation error and i am not able to understand exact reason

Exception in thread "main" java.lang.NoSuchMethodError: Dog.<init>        (ILjava/lang/String;)V
at SuperNotSerial.main(SuperNotSerial.java:5)
Was it helpful?

Solution

Adding to fge answer that you are missing a no argument constructor required for serialization.

To know the need for a no-argument constructor while serialization we need to understand the process in which serialization takes place. Serialization works by chaining up each class in the inheritance hierarchy and then saving the state of each superclass until the first non-serialization class is reached.

Now, when we try to deserialize the object, the state of the non-serializable super class (which is required to construct the exact state of the object) can not be restored from the stream, and is instead restored by invoking the no-arg constructor.

The problem arises when the no-arg constructor of the first non-serializable class is not accessible, throwing an exception 'InvalidClassException: no valid constructor'.

As we know by default each Java class has a no-arg constructor. So, how can it be inaccessible some times?

The answer is: the default no-arg constructor is invoked only if no other constructor with arguments is declared in the class. In this case, in order to invoke the no-arg constructor we need to declare it separately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top