title: Change class variable type in subclass java
body: <p>I have a class called "Module"</p>
  
  <pre><code>public abstract class Module {
  
      protected Map&lt;String, Port&gt; ports;
  
      ...
  
      public Map&lt;String, Port&gt; getPorts() {
          return ports;
      }
  }
  </code></pre>
  
  <p>and a class called Design that is a subclass of Module</p>
  
  <pre><code>public class Design extends Module{
      ...
  
      //want to do this but doesn't compile
      @override
      public Map&lt;String, Port&gt; getPorts() {
          return (Map&lt;String, TopPort&gt;) ports;  //TopPort is a subclass of Port
      }
  }
  </code></pre>
  
  <p>Basically what I want to do is only add TopPorts to Design and have the type already cast upon return from the getPorts() function.</p>
  
  <p>What I am doing right now is casting Ports to TopPorts after the getPorts function returns in main, but this is very finneky and someone who is building on my code would not be able to immediately understand when a TopPort is returned.</p>
  
  <p>I also tried creating another function instead of overriding getPorts()</p>
  
  <pre><code>    //want to do this as well but doesn't compile
      public Map&lt;String, TopPort&gt; getTopPorts() {
          return (Map&lt;String, TopPort&gt;) ports;  //TopPort is a subclass of Port
      }
  </code></pre>
  
  <p>What is the correct way to do this?</p>
  
  <hr>
  
  <p><strong>More specific problem</strong></p>
  
  <p>I have been playing around with the code and I am able to add this in my "Design" class:</p>
  
  <pre><code>public TopPort getTopPortByName(String porName) {
      return (TopPort) ports.get(porName);
  }
  
  public void addPort(TopPort port) {
      this.ports.put(port.getName(), port);
  }
  </code></pre>
  
  <p>However whenever I try to do this casting, it doesn't work:</p>
  
  <pre><code>return (Map&lt;String, TopPort&gt;) this.ports;
  </code></pre>
  
  <p>Why does the type-cast not work on the whole map even though it works on each of its members?</p>