title: How to get subclass in a class map
body: <p>Im having some trouble with classes in java, I am making a component system which uses a HashMap like so</p>
  
  <pre><code>private final Map&lt;Class&lt;? extends Component&gt;, Component&gt; components = new HashMap&lt;&gt;();
  </code></pre>
  
  <p>Component is the base type for all components, I make an abstract class called Material which is extends Component.</p>
  
  <pre><code>public abstract class Material extends Component
  </code></pre>
  
  <p>This forces me to extends this somewhere else to use it, for my example I make a TerrainMaterial</p>
  
  <pre><code>public class TerrainMaterial extends Material
  </code></pre>
  
  <p>I add a component with the following method</p>
  
  <pre><code>public &lt;T extends Component&gt; T addComponent(T component) {
  
      if (containsComponent(component.getClass())) return null;
  
      components.put(component.getClass(), component);
      return component;
  
  }
  </code></pre>
  
  <p>In my rendering class it goes back to this HashMap to try and get the material type.</p>
  
  <pre><code>entity.getComponent(Material.class);
  </code></pre>
  
  <p>This internally calls this method, the containsComponent method is a comple containsKey check</p>
  
  <pre><code>public &lt;T extends Component&gt; T getComponent(Class&lt;T&gt; component) {
  
      if (!containsComponent(component)) return null;
  
      return component.cast(components.get(component));
  
  }
  </code></pre>
  
  <p>The issue comes when trying to return this value, because the TerrainMaterial has a class type of TerrainMaterial and not Material it fails to find it, How can i go about making this return TerrainMaterial when using Terrain.class.</p>
  
  <p>Note that i have tried adding the component like this and with casting and no change.</p>
  
  <pre><code>terrainEntity.&lt;Material&gt;addComponent(new TerrainMaterial(...));
  </code></pre>
  
  <p>Thanks in advance</p>