title: Java HashMap to store different objects
body: <p>I have a problem with HashMap. This problem is same for any other generics (LinkedList etc). Let's say that I have 2 classess:</p>
  
  <p>Class A:</p>
  
  <pre><code>public class A {
      public void aMethod() {
          System.out.println("A");
      }
  </code></pre>
  
  <p>Class B, extends A:</p>
  
  <pre><code>public class B extends A {
      public void bMethod() {
          System.out.println("B");
      }
  </code></pre>
  
  <p>Now in the class with main method I'm making a hashmap to store instances of this 2 classess:</p>
  
  <pre><code>import java.util.HashMap;
  
  public class TestList {
      public static void main(String[] args) {
  
          //I'm making 2 objects representing A and B class:
  
          A objA = new A();
          B objB = new B();
  
          // I'm making a HasMap storing A class objects, where I can
          // also store B objects, because B is subclass of A
  
          HashMap&lt;String, A&gt; myObjects = new HashMap&lt;String, A&gt;();
          myObjects.put("objA", objA);
          myObjects.put("objB", objB);
  
          // using a method from class A is working fine on objA: 
          myObjects.get("objA").aMethod();
  
          // but if I want to use a method from B class on objB
          // I need to cast:
          ((B) myObjects.get("objB")).bMethod();
  
      }
  }
  </code></pre>
  
  <p>Is there any way to store object from different classess in one HashMap, which doesn't require casting to use other (extended) methods ?</p>
  
  <p>I'd like to use:</p>
  
  <pre><code>myObjects.get("objB")).bMethod();
  </code></pre>
  
  <p>Without casting. Thank you.</p>