0

Suppose we have the following classes:

class Packet implements Serializable { ... };
class OpenConnectionPacket extends Packet { ... };
class DataPacket extends Packet { ... };
class CloseConnectionPacket extends Packet { ... };

Now, I want to be able to send an arbitrary packet like this:

Socket s = ...;
ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream());

Packet p = ...;

toServer.writeObject(p);

and recieve it from the other end:

Socket s = ...;
ObjectInputStream fromClient = new ObjectInputStream(s.getInputStream());

Packet p = (Packet) fromClient.readObject();

Is this possible? How? (If it is, I guess is should override the writeObject() and readObject() methods, and maybe have something like a int type; or some enum in the parent class Packet in order to identify each child?)

José D.
  • 4,175
  • 7
  • 28
  • 47

1 Answers1

1

You don't need to override writeObject() and readObject().

It works by its default implementation until and unless you write your custom logic while serialization if needed.

For more info have a look at below links

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76