简体   繁体   中英

new Object.getClass()

Is there a way to make a new Object of the type of another?

Example:

Soldier extends Person
Accountant extends Person

Each subclass of Person has a constructor that accepts (BirthDate and DeathDate)

I have a method called prepPerson(Person) and it accepts a Person. I would like to have a JComboBox populated with Person objects of different types (Accountant, Soldier) that I call .getSelectedItem() and get back a Person object.

As I am only using those Person objects to populate the JComboBox menu how do I detect the type of person selected, make a new Soldier or Accountant object so that I can pass it to the prepPerson method?

Use either instanceof or create method getType() on Person which return enum - the type of the Person .

But when you start using instanceof in such situation you may consider to change the desing somehow.

Could you describe why do you need to distinguish them later?

If you're going to have a finite number of selections, do this:

Person thePerson = null; // note, don't call variables theAnything... it's just bad

JComboBox theBox = new JComboBox(new String[]{"Accountant","Soldier","Programmer"});



// later

public void actionPerformed(ActionEvent e) {
        if(e.getSource() == theBox) {
            String who = (String)theBox.getSelectedItem();
            if(who.equals("Accountant") thePerson = new Accountant();
            if(who.equals("Soldier") thePerson = new Soldier();
            if(who.equals("Programmer") thePerson = new Programmer();
        }
}

Why do you need to detect the type? You have a Person and you must pass a Person to the new method.

You are likely to find seperating Roles/Types from a Person useful. This way any Person can have one or more roles which can change at any time.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM