Let's say I instantiate a HashMap with SuperClass
as value-type. I then add SubClass
objects as values to the Map. When I retrieve those values from the Map, they are returned as objects of type SuperClass
, which I explicitly cast back 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 is of the specific SubClass
because I want to access methods that only exist in the SubClass. If the returned type can be any number of different SubClasses, is the use of instanceof
considered best practice in determining the type and the casting?
SuperClass s = map.get("1");
if (s instanceof SubClass1) {
(SubClass1)s.one = 1;
}
Thanks
There are a number of ways about this depending upon the particular situation:
The best practice should be putting each SubClass type inside a different Map.
Using instanceof before performing a cast, if you really need to do that cast, it's a good idea because this way you will prevent a ClassCastException.
Pay attention that if your code has a lot of instanceof directives then you could have a bad design.
If you want to put them in the same Map then you need to think about your design:
have your DoSomething class to be aware of the differents SubClass types to perform specific operation?I see 3 possibilities:
Yes, you should definitely use instanceof to be typesafe. Otherwise, how would you know whether or not the object you pulled out is in fact the correct subclass?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.