Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface with two different implementations

I have an interface Person and I have 2 classes Female and Male that implement the interface.

For the Female class, I have a method getPregnancyMonth that my Male class does not have. Adding that method to my interface Person becomes a problem as my Male class now needs to inherit that method from the interface; but the male would never be pregnant.

What would be a solution, do I need to extend Person instead of implement?

EDIT: Sorry if my question wasn't clear. In this case I have added both get/set methods from the Male and Female classes to the interface.

    static void Main(Form form) {
        Person person = Factory.createPerson(form.getGender());
        person.setName(form.getName());

        if ("F".equals(gender)) {
            person.setPregnancyMonth(form.getPregnancyMonth());
        }
    }

My question is, since my interface has getPregnancyMonth, my male has to add that method to the concrete class to implement the interface. Is there a way to avoid this?

like image 602
gathcea Avatar asked Aug 16 '11 02:08

gathcea


1 Answers

getPregnancyMonth Should not be in the interface of Person.

Personally...no pun intended...I think you should create Person as an abstract class as female and male will share a lot of the same attributes and functions.

Then you could create Female and Male interfaces that reflect unique functionality for each sex.

like image 173
Shawn Avatar answered Nov 05 '22 14:11

Shawn