Why Java Lang.void cannot be serialized?

By default, the primitive 'void' can be serialized. Why can't the object 'void' extend serializable?

Add example:

Rootimplementation will have a compilation error saying "void is not in its scope" because it does not extend serializable Although 'somemethod' is declared as' void ', there will be no problem

public interface Root<R extends Serializable> extends Serializable {
  R someMethod();
}

public class RootImplementation implements Root<Void> {
  public Void someMethod() {
    return null;
  }
}

Solution

Well, in response to your example, if you change the method to void, it won't work because the method must have a return type (even if Java now allows covariant return types in rewriting methods) The invalid discussion confused the problem

What you want to do is declare a type parameter as "will only return null" Void is usually a good choice, but for void to work, the return type must be object Void cannot implement every interface in the API because someone might want to use it to indicate a null return of a type parameter

There are three ways to view your questions:

>Serializable is an overly strict type declaration You should really use object Do you really need it to be serializable? > You can declare the type parameter serializable and actually return null This doesn't exactly mean that you return null every time, but it may be enough. > You can declare your own class named null, which implements serializable, possibly as a static nested class of the root interface, and in this case use it as a type parameter You will find that it is not common to make your own null objects. There are (private) objects even in the standard JDK

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>