Java best practices. Put / Get SubClass objects in a HashMap that expects SuperClass objects.

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

+4
source share
3 answers

Depending on the specific situation, there are several ways:

  • Add an abstract method to the superclass to perform the corresponding operation.
  • Use the adapter as the type of map value. When adding entries, use the adapter specification to match the subtype.
  • Separate cards. Especially good if they should not be on the same card in the first place.
+4
source

It is best practice to place each type of SubClass inside another Map.

Using instanceof before doing the cast, if you really need to do this, is a good idea, because that way you will prevent a ClassCastException.

Note that if your code has multiple instances of directives, then you may have poor design.

If you want to put them on the same card, you need to think about your design:

Do you have a DoSomething class that needs to know the different types of SubClass to perform a specific operation? I see 3 possibilities:

  • Yes, DoSomething should know all your SubClass types. Then don’t worry, check with instanceof and discard the object extracted from the map, or, better, save them on different Maps.
  • No, DoSomething does not need to know about another SubClass, because it can use them for the general SuperClass interface. This is a good design.
  • You do not want DoSomething to know about the different types of SubClass, but in a certain situation you feel the need to use some subclasses for specific methods: code refactoring, incorrect design.
+2
source

Yes, you should definitely use instanceof for types. Otherwise, how would you know if the object you pulled out is the correct subclass?

0
source