Say I'm creating an instance of a HashMap with SuperClass as a value type. Then I add SubClass objects as values ββto the Map. When I extract these values ββfrom the Map, they are returned as objects of type SuperClass , which I explicitly return to SubClass :
class SuperClass {} class SubClass1 extends SuperClass { int one;} class SubClass2 extends SuperClass { int two;} class DoSomething { DoSomething() { Map<String, SuperClass> map = new HashMap<String, SuperClass>(); map.put("1", new SubClass1()); map.put("2", new SubClass2()); SubClass1 one = (SubClass1) map.get("1"); } }
I need to know that the returned object has a specific SubClass , because I want to access methods that exist only in SubClass. If the return type can be any number of different subclasses, is instanceof using best practice for determining type and cast?
SuperClass s = map.get("1"); if (s instanceof SubClass1) { (SubClass1)s.one = 1; }
thanks
source share