Srinivas Srinivas - 9 months ago 30
Java Question

Clarification on Java Serialization

I am learning Serialization and came across this function (in Externalization).

public void writeExternal(ObjectOutput oi) throws IOException, ClassNotFoundException

I understand that the method creates an object named oi of type ObjectOutput for writing instance variables to the object. When I wanted to learn more about the class ObjectOutput, I was surprised that ObjectOutput is an interface! I thought Java does not allow objects to be created of type interface. Please let me know why this is the case or correct me if I have understood something wrong.


First of all, as trappski pointed out in the comments, writeExternal doesn't create anything. ObjectOutput is a parameter passed into it by whatever code is calling writeExternal.

The trick with interfaces is that they're a "contract". You can't create objects from interfaces, but you can create classes that implement the interface, and then create objects from those classes. You can then use objects of those classes that implement the interface anywhere that is expecting the interface.

In this case, if you have a class BigObjectOutput that implements ObjectOutput like so:

class BigObjectOutput implements ObjectOutput {
  // code...

then you can create an object of type BigObjectOutput like this:

BigObjectOutput bigObject = new BigObjectOutput;

And pass it into your method because BigObjectOutput implements ObjectOutput:


Why would you want to do this? So that you can pass in any object whose type implements ObjectOutput:

class LittleObjectOutput implements ObjectOutput {
  // code...

LittleObjectOutput littleObject = new LittleObjectOutput();


So your writeOutput is more useful if it accepts any object whose type implements the OutputObject interface than if it only took BigObjectOutputs.