title: Polymorphism of objects through a stream in java?
body: <p>I'm writing code for a university project. We have to implement a board game to be played remotely and in multiplayer.</p>
  
  <p>We are currently using the request-response pattern: the clients send the requests to the server through an IO stream and the server analyzes them and returns the correct responses.</p>
  
  <p>The problem is that we have many types of requests and we are using polymorphism to understand which request is the one received: </p>
  
  <pre><code>/**
   * This method is only functional to polymorphism: it should never be invoked.
   * @param request
   * @return only an assertion error
   */
  public ResponseMsg handleRequest(RequestMsg request) {
  
      throw new AssertionError("It was created a RequestMsg. This should never happen.\n"
  }
  
  /**
   * The request is to change the map. 
   * If the game is not started and the player is the first, the map will be changed and
   * a broadcast with the new map will be sent to all the players.
   * @param request: the request containing the name of the map chosen
   * @return An ack response message
   */
  public ResponseMsg handleRequest(ChangeMapRequestMsg request) {
  
      if (game != null)
          return new InvalidRequestMsg("You can't change the map when the game is already started");
  
      else if (request.getToken().getPlayerNumber() != 0)
          return new InvalidRequestMsg("Only the first player can change the map");
  
      else {
  
          this.map = request.getMap();
  
          BroadcastMsg broadcast = new ChangedMapBroadcastMsg(request.getMap());
          publisherInterface.publish(broadcast, getLobby());
  
          return new AckResponseMsg("Map changed successfully");
      }
  }
  
  /**
   * Handles a chat message
   *  it sends a broadcast containing the message to all the players and an 
   *  acknowledgement to the player who sent it
   *
   * @param the chat request from the player
   * @return the acknowledgement
   */
  public ResponseMsg handleRequest(SendChatRequestMsg request) {
  
      ChatBroadcastMsg chatBroadcast = new ChatBroadcastMsg(players.indexOf(request.getToken()), request.getMessage());
      publisherInterface.publish(chatBroadcast, getLobby());
      return new AckResponseMsg("Chat message sent.");        
  }
  </code></pre>
  
  <p>The problem is that when we send the requests to the server, we need to pass them through an output stream and it will read them through an input stream. We are forced to cast them as <code>Object</code>, and thus we lose the possibility to exploit polymorphism.</p>
  
  <p>How can we maintain the ability to exploit polymorphism? We'd like to not use <code>instanceof</code> to get the dynamic type of the request as our professor told us never ever to do that.</p>