i am new in Java and i try to make some really simple java applications. In my attempts i have come to problem with generalisation. I have a list of Person objects. Person can be Father or Mother.
Then, i have couple of methods with same name eat(...) but they differ in input parameters. These methods are not part of Person class. One of these methods accepts Mother as parameter and the other accepts Father.
The question is how to dynamically decide which method to invoke on list of Person. when i try iterating through list and calling o.eat(iterator) it prompts with compiler error, because iterator is of type Person but my eat methods want Mother or Father as parameters. Compiler doesnt know that i have method for each type of Person
Thus far i have solved my problem with if statement in which i compare the class type by GetType() method with both Mother and Father and if it equals i can cast Person into appropriate type.
Code looks like this:
if (person.getClass().equals(Father.class)) {
theView.eat((Father) person);
}
if (person.getClass().equals(Mother.class)) {
theView.eat((Mother) person);
}
Eat method looks as follow:
public void eat(Mother m){
textArea.append(m.breakfast);
textArea.append(m.lunch);
textArea.append(m.dinner);
}
lunch dinner and breakfast are just some string indicating what the person is doing
person is the code is iterator through list of Person objects
Is there any better solution which will automate the proccess?
Thx in advance.