0

I have a JComboBox where the user can choose from 94 different options, represented by strings, which correspond to 94 different classes.

All the 94 classes inherit from one parent class, called AbstractTiling. After Choosing one of those options (Strings from ComboBox) the chosen class should be instantiated. But since there are 94 different possibilites I don't want to use 94 if statements. So I tried it with a hashmap, but this leads to the problem that I still don't know the exact type I want to instantiate, so I can't use the methods that the classes overwrite from the parent class or have that the parent class doesn't.

In the code example there are just two entries in the hasmap as an example. Here is the code:

JComboBox groupscb = new JComboBox(isohedrals);
groupscb.setSelectedIndex(52);
groupscb.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        int selectedItem = ((JComboBox)arg0.getSource()).getSelectedIndex();
        Map <Integer, Object> hm = new HashMap<Integer, Object>();
        hm.put(52, new IH52());
        hm.put(55, new IH55());
        //here I want to instantiate the class, since I don't know it
        //I used the parent class. But this keeps me from using the 
        //child classes methods
        AbstractTiling tiling = (AbstractTiling) hm.get(selectedItem);          
    }
});
  • The method you want to call from your actionPerformed() method should be declared in the common abstract class. That's what polymorphism is all about. – JB Nizet Mar 16 '14 at 17:04
  • @JB Nizet The problem is that the the 94 classes override some methods from the parent class and implement additional methods. So I wouldn't be able to access these methods, if I cast the returned object to AbstractTiling/ parent class. Or would I? – user3426102 Mar 16 '14 at 17:40
  • You want to doSomething() with the selected item when it's selected. So add doSomething() in the base class, and override it in every subclass to do the appropriate thing. – JB Nizet Mar 16 '14 at 17:43
  • If I understand his question correctly, he doesn't have an instance of the subclass, he merely has a string with the name of the subclass. – Roy Mar 16 '14 at 18:45

1 Answers1

0

I think you can do it using the Class class. These links have more info.

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

How do I get a class reference from a String in Java?

Good luck!

Community
  • 1
  • 1
Roy
  • 974
  • 6
  • 11