简体   繁体   中英

Extending class with private constructor in Serializable class

The document detailing Serializable on http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html

says

"To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime."

In general any class with private constructor cannot be extended. And this error will be visible on compile time. But the last line the above documentation says it will occur at run time. Any explanations?

The document says that a non-serializable supertype needs a no-arg constructor. It does not say it should be private. On the contrary it says this constructor should be accessible. What the documentation means about runtime is this

class A {
    A() {   <-- accessible only in current package
    }
}

public class B extends A implements Serializable {
    public B() {
    }
}

Lets assume both A and B are in the same package. There is no compile error. But if we try to deserialize an instance of B from class C in another package we will get a runtime exception, because ObjectInputStream will try to invoke A's no-arg constructor but it is inaccessible from outside the package

Your last part of explanation is not correct. It doesn't matter if A's no-arg constructor is visible to C or not. It only needs to be visible to B.

In a nut shell, B can be declared serializable as long as A has a no-arg constructor which is visible to B.

But the original is still open:

Why this error is identified during run time when all validation information is available during compile time?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM