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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With