Java Serialization Issue - java

When I serialize the abstract class does the inheriting subclasses will also be serialize?
Does this include the members of abstract class and its subclasses?
public abstract class RootClass implements Serializable{
Object data;
}
public class SubClassA extends RootClass{
Object dataA;
}
public class SubClassB extends RootClass{
Object dataB;
}
Now when I instantiate class SubClassA and SubClassB and I will serialize those instances it is possible?
Will it include members of subclasses and root class?

Not sure if I understand the question. I'll try to answer anyway.
When you declare an abstract class Serializable, this interface is also inherited by subclasses, so they are considered Serializable and will also have to be made serializable (if you do nothing, the default serialization mechanism will be applied to it, which may or may not work).
You only serialize object instances, not classes.
The default serialization serializes fields of a parent class, too, but only if that parent class is also Serializable. If not, the parent state is not serialized.
If you serialize an object of an abstract class' subclass, and the abstract class is Serializable, then all fields in that abstract parent class will also be serialized (the usual exceptions apply, such as transient or static fields).

Serialization is for 'objects' and saving their state and not for the classes. Since you cannot create instances for abstract classes, there is no point in discussing whether they can be serialized in the first place.

When you instantiate an object of a certain class, its data is comprised of two parts: fields defined by its class and fields defines by superclasses. Mind you, not all inherited fields are accessible, only those defined as protected or public (or unmodified when in the same package).
If the object's class is Serializable, its fields will be serialized (unless marked transient), and the same is true for inherited fields. In your case, an instance of SubClassA will contain both 'data' and 'dataA', and because both class and subclass are Serializable, both fields will be serialized. After deserialization, both fields should be accessible.

Related

Default Superclass in Java

I was reading an article on Inheritance . Few facts were listed on Inheritance but one point i couldn't understand what is Default superclass and its explanation. What is Default superclass?
Default Superclass : Except Object class, which has no superClass, every class has one and only one direct superclass(single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class.
The default superclass is Object (more precisely java.lang.Object). If a class does not define a direct superclass explicitly (via extends), then Object is implicitly a superclass of that class.
Have a look at the following example which graphically shows this:
public class A {}
public class B extends A {}
public class C {}
Note that his rule does not apply to Object itself since this would produce a cyclic inheritance. In other words, java.lang.Object is the root of the class hierarchy.
Except Object class, which has no Super Class, every class has one and only one direct superclass(single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class
Points to understand first:
There is a class Object in java which is already available with the JRE libraries.
When you define a class without an extends keyword, your class will by default extend the Object class in Java.
Even if you extend another class in your new class, the parent or its parent transitively inherits the Object class.
Simple way to understand - after you define a class with / without a parent class, create an object for it. If you are using an IDE, you can see that there are some method suggestions which is not implemented in your class (or parent ). Methods like clone() equals() hashCode() wait() etc. Where did these methods/ behaviors come from to your object ? - Yes it came from the ultimate parent Object
The default inheritance is implicit and handled by the Java itself. Hope this makes your understanding better.
object class is base class for every class you create.
when you create an object of your class then constructor of object class is called.
The Object class in Java is the default superclass. Object class is inherited into a newly created class by default if it does not explicitly inherited from any other class. So every class that you create in Java programming is inherently a child class of the Object.
All classes in Java extend Object class by default, and they are subclass of object class, the only exception of this convention is the Object class itself, object class does not extend any class by default, this is the whole idea.

When saving a Serializable object, does everything referenced need to be Serializable too?

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.

Serialization with Super class and Sub class

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.

Non-transient non-serializable instance field in serializable class

Consider the following code :
public class LIMSGrid extends ClientEventSource implements Focusable, FramingBlockWrapper {
//cell that is curently in edit mode
private CellCoord editingCell = null;
//framing block info
private FramingBlock framingBlock;
}
Now ClientEventSource extends a class that implements Serializable interface . The classes CellCoord and FramingBlock are POJOS with a bunch of getters and setters . FindBugs is complaining about the editingCell and framingBlock fields saying :
This Serializable class defines a non-primitive instance field which
is neither transient, Serializable, or java.lang.Object, and does not
appear to implement the Externalizable interface or the readObject()
and writeObject() methods.  Objects of this class will not be
deserialized correctly if a non-Serializable object is stored in this
field.
Okay so everything is fine except how come it is saying that the instance fields are not "java.lang.Object" . This is totally misleading or I am missing some basics here ?
My guess (but it's only a guess) is that FindBugs doesn't trigger this warning if you reference java.lang.object instances, because it considers that in this case, your class is a generic container, which can hold any kind of object (like a Collection).
In that case, it's the responsibility of the user of the class to make sure that the object stored in the container is serializable if he wants the container to be serializable. (just like an ArrayList is serializable if and only if you store serializable objects inside the list).
You should make CellCoord and FramingBlock serializable to avoid that error. If you don't want to serialize them, you should set them as being transient.
The objects of the classes will not be deserialize correctly if there is any one of the object defined in the class extending the serializable will have non-primitive instance field which is neither transient, Serializable. because if any object of class want to save the its state , it won't be able to do so just because of one non-primitive instance field which is neither transient, Serializable.

Inheritance of Object Class in Java

While i was reading java book, i came across "Every class extends class Object"...but if want a class B to extend class A.....but Class B will be now having multiple inheritance,one from Object class and one from Class A.How the conflict is resolved.
Can anyone explain?
Its multi-level inheritance, not multiple:
class A extends Object
class B extends A
First of all, Object class is the super/base/parent class of every class including user-defined classes.
So even if we don't mention it explicitly, the user-defined classes extends Object class by default.
Morevoer, Object class implements a set of methods and variables which are common to all the objects being created in the application. This is the main reason why we have Object class as a base class for all the other classes.
For eg:
hashCode() - this method creates a unique identity for each of the object being created in JVM.
ClassB extends from ClassA which also extends from Object. Therefore ClassB extends Object indirectly, through classA
"Every class extends class Object" just means if you don't specify the parent class, it takes on Object as the parent class
The book was trying to explain that every class is either a direct or indirect subclass of Object. Among other things, this means that every class inherits the public methods of Object: toString(), hashcode(), wait(), etc. It also means that whatever class variable a happens to be, you can always assign a to a variable of class Object.
There is no such thing as multiple inheritance in Java. The closest Java comes to that is interfaces, which is a whole subject in itself.
there is no conflict.. take a look at this structure
animal
bird
sparrow
parrot
dog
poodle
cat
the parrot class gets all attributes/methods of its super-class bird and from its super-class animal. this is called multiple inheritance.
You get traits from your parents right? You also get traits from their parents also.

Categories