I thought class that implements an interface must implement all of the interface's methods,why classes that implements Serializable interface implements none interface's methods ?
Some interfaces act simply as markers for classes. Serializable is one of them. The methods are there only in case your object requires special handling in order to be serialized and deserialized.
Because Serializable is only a "marker" interface for object serialization and has no methods defined. From the Javadoc:
The serialization interface has no methods or fields and serves only
to identify the semantics of being serializable.
And from SDN:
An object is marked serializable by implementing the
java.io.Serializable interface, which signifies to the underlying API
that the object can be flattened into bytes and subsequently inflated
in the future.
Related
I learned about implementing Serializable in school but it was never mentioned what, if any, objects are already doing this in Java. So my question is in the title "Are there some objects or data types that are automatically serialized by Java (without having to implement Serializable)?" and if so what are they are what is the reasoning behind it?
Javadoc is clear (emphasis is mine):
Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
But to answer to :
"Are there some objects or data types that are automatically
serialized by Java (without having to implement Serializable)?"
The answer is yes as the Javadoc adds that :
All subtypes of a serializable class are themselves serializable.
Here is a more detailed answer :
1) Primitives are de facto serializable.
2) A very important number of JDK classes implement Serializable. Which makes sense as these cannot be modified by clients and could so not be serialized. Here is the "Uses of Interface java.io.Serializable" generated in the javadoc. The list is huge.
3) Every array type implements the interfaces Cloneable and java.io.Serializable for exactly the same reason that other JDK classes are.(JLS 10.1 Array Types).
4) All subtypes of a serializable class are themselves serializable.
For example javax.swing.JComponent that is the base class for all Swing components except top-level containers implements Serializable :
public abstract class JComponent extends Container implements Serializable,...{...}
As a consequence, its child classes don't need to implement directly Serializable and indeed the very most of them don't do it.
For example :
public abstract class AbstractButton extends JComponent implements ItemSelectable, SwingConstants {...}
public class JButton extends AbstractButton implements Accessible {...}
public class JComboBox<E> extends JComponent{...}
We could see a similar thing for Number that is the base class for numeric values.
Number implements Serializable :
public abstract class Number implements java.io.Serializable {...}
And many subclasses implement Serializable by transitivity :
public final class Integer extends Number implements Comparable<Integer> {...}
public final class Float extends Number implements Comparable<Float> {...}
But note that the subclasses of classes implementing Serializable may also explicitly implement java.io.Serializable such as :
public class AtomicInteger extends Number implements java.io.Serializable {...}
It is probably done to make the information more explicit in the source code.
But it could also be helpful in case of code where the code is unstable and the hierarchy may change. Whatever the change, the class goes on to be serializable.
Yes. All array types are automatically serializable. JLS #10.1
If I extend a class that implements Serializable, do I need that class to also implement Serializable?
For instance if I have,
public class classToBeExtended implements Serializable
Then will this suffice?
public class classThatWillExtend extends classToExtended
Or do I need to do this?
public class classThatWillExtend extends classToExtended implements Serializable
If any of a class's superclasses implements a given interface, then the subclass also implements that interface. Serializable is not special in that regard, so no, the subclasses of a Serializable class do not need to explicitly declare that they implement Serializable. They can so declare, but doing that makes no difference.
The other implication is that if you extend a Serializable class, you should ensure that the subclass is indeed serializable itself. For example, don't add non-transient fields of non-serializable types unless you're prepared also to add the necessary methods to support them.
Per Javadoc:
All subtypes of a serializable class are themselves serializable
I have a doubt about Interfaces in JAVA:
When a class implements an interface, does anything happen to it if it does not implement its methods? Merely implementing the interface , does it provide any change of meaning to the class ?
For example I have two classes, Test1 and Test2
public class Test1 implements Serializable {
}
public class Test2 {
}
Except for the fact that Test1 implements Serializable, the classes Test1 and Test2 are identical. In that case would there be any difference between the functionalities/properties of objects of Test1 and Test2? Would it be possible to break down objects of Test1 class into bytes (just because class Test1implements Serializable)?
If yes, then that means implementing an interface provides some additional meaning to the objects of that class?
Straight from documentaion of Serializable -
Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
The serialization interface has no methods or fields and serves only
to identify the semantics of being serializable.
Link
Q1> In that case would there be any difference between the functionalities/properties of objects of Test1 and Test2?
Serializable is marker interface, which means there no method or field.
Q2> Would it be possible to break down Objects of Test1 class into bytes (just because class Test1 implements Serializable?
Yes.
Q3> If yes, then that means implementing an interface provides some additional meaning to the objects of that class?
Object Serialization produces a stream with information about the Java
classes for the objects which are being saved. For serializable
objects, sufficient information is kept to restore those objects even
if a different (but compatible) version of the implementation of the
class is present.
Thhe class can optionally define the following methods:
A writeObject method to control what information is saved or to
append additional information to the stream
A readObject method either to read the information written by the
corresponding writeObject method or to update the state of the object
after it has been restored
A writeReplace method to allow a class to nominate a replacement
object to be written to the stream
Link
It depends on the definition of the interface you decide to implement.
In the example you took one of the classes implemented serializable interface; it being a marker interface you did not have to overload any of its method. But there is as you know a difference between the two classes, while objects of Test1 class can be converted to stream of bytes for external storage such feature is not available for Test2 objects. Also, there is a serialId class member which Test1 has but Test2 does not.
This was a specific case; but lets say the interface you implemented had abstract methods, then in this case Test1 class either had to also be an abstract class or it had to provide a concrete definition to those abstract methods of the interface. In such a scenario Test1 and Test2 classes would have varied a lot from each other. FYI,The interface body can contain abstract methods, default methods, and static methods.
In Java 8+ it's possible for an interface to provide a default method. For example 13.5.6-1. Adding A Default Method (which means an interface can add method implementations),
interface Painter {
default void draw() {
System.out.println("Here's a picture...");
}
}
However, Serializable is a marker interface (and Wikipedia says, in part) the mere presence of such an interface indicates specific behavior on the part of the implementing class. You might want to compare it to Externalizable.
An interface, in its most basic form, is a set of empty methods which define some core functions. A class which implements an interface will be required to include all of its methods.
However, interface Serializable does not have any methods. It simply states "this object can be serialized," and they sometimes rely on other special methods (readObject(), writeObject(), etc.) for handling.
Here's a quote from Javadocs:
Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
The serialization interface has no methods or fields and serves only
to identify the semantics of being serializable.
Therefore a class can only be serialized if it implements interface Serializable.
This may be obvious, but I'm not quite getting my head around Serialization:
I have a single object which holds the state of my application. This object references multiple other objects.
eg
ApplicationState implements Serializable
private ArrayList<SomeApplicationObjects>
private AnApplicationObject
private AnotherObject
All of these objects (someApplicationObjects, anApplicationObject, anotherObject) need to be serializable, as far as I understand.
But do objects THEY reference also need to be serializable? eg does SubObject here need to be serializable too? Does this essentially mean that every sub-object needs to be Serializable, recursively, from the ApplicationState down?
AnotherObject implements Serializable
private SubObject
Does this essentially mean that every sub-object needs to be Serializable, recursively
Assuming sub-object is the object you are using inside the class. Yes, the Objects used inside your Searializable type also be serializable.
Where as
All subtypes of a serializable class are themselves serializable
Yes, as reported in the javadoc of the interface serializable:
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable.
So if A has to be a serializable, subtypes of A (eg. B and C) have to be serializable too. So B and C should have also subtypes that are serializable, and so on..
As mention in java doc for serialization;
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.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.
It is mandatory that all sub-object need to be serializable.
My doubt is using Scenario 1 it is possible to achieve serialization . If I extend one abstract class which is serializable by many sub classes means , is this possible to achieve ?. As I tried with Scenario 2.
Serializable will be applicable for all beans or not,Please help me.
my doubt scenario 1 and scenario 2 will be same or different.
//method to send message ::: sendMsgs(SerializableObject)
Scenario 1:
public class EmailMaster implements Serializable
{
// setters and getters
}
Scenario 2:
public abstract class MessageBean implements Serializable
{
}
//whether EmailMaster and EmailEvent will become serializable ?
public class EmailMaster extends MessageBean
{
// setters and getters
public class EmailEvent extends MessageBean
{
// setters and getters
}
This should be Serialilzable. When you extend MessageBean, all extending classes of MessageBean be default inherit the Serializable interface from MessageBean abstract class.
I would advice to have unique serialVersionUID assigned in each extending(sub) classes.
EDIT: From Searialization perspective, scenario1 and sceanrio2 are not different but theoretically they are different as you are having an additional abstract class in sceario2, which can have more methods/attributes, which will also get available to the EmailMaster class.
In both the scenarios: sendMsgs(SerializableObject) should work. Make a decision between sceanrio1 and scenario2 based on the need of abstract class in between. If you don't need the abstract class for any other purpose, go with scenario1.
Serializable is inherited by all the subclasses of the abstract class as for any other interface:
If A implements Serializable, whatever class extends A will be Serializable
So both Scenarios will work but in any case a concrete Serializable class must have a no-args constructor. See the following Serializable Javadoc:
Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
All subtypes of a serializable class are themselves serializable. The
serialization interface has no methods or fields and serves only to
identify the semantics of being serializable.
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.
Moreover, regarding the Serial Version ID of the object:
The serialization runtime associates with each serializable class a
version number, called a serialVersionUID, which is used during
deserialization to verify that the sender and receiver of a serialized
object have loaded classes for that object that are compatible with
respect to serialization. If the receiver has loaded a class for the
object that has a different serialVersionUID than that of the
corresponding sender's class, then deserialization will result in an
InvalidClassException. A serializable class can declare its own
serialVersionUID explicitly by declaring a field named
"serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a
default serialVersionUID value for that class based on various aspects
of the class, as described in the Java(TM) Object Serialization
Specification. However, it is strongly recommended that all
serializable classes explicitly declare serialVersionUID values, since
the default serialVersionUID computation is highly sensitive to class
details that may vary depending on compiler implementations, and can
thus result in unexpected InvalidClassExceptions during
deserialization.
Try
Serializable emailMaster = new EmailMaster();
If it works then EmailMaster is-a Serializable. AFAIK, that definitely should work.