I have a problem with HashMap. This problem is same for any other generics (LinkedList etc). Let's say that I have 2 classess:
Class A:
public class A {
public void aMethod() {
System.out.println("A");
}
Class B, extends A:
public class B extends A {
public void bMethod() {
System.out.println("B");
}
Now in the class with main method I'm making a hashmap to store instances of this 2 classess:
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<String, A> myObjects = new HashMap<String, A>();
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();
}
}
Is there any way to store object from different classess in one HashMap, which doesn't require casting to use other (extended) methods ?
I'd like to use:
myObjects.get("objB")).bMethod();
Without casting. Thank you.