Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Inheritance in C#

So I just had a job interview and they gave me a list of tasks that they wanted me to work on beforehand. I finished all of the tasks except for one and was wondering if anyone could shed some light on the question.

The question went something like this

  1. Create a class called Human, give the class a public property HairColor and a public method Talk() that, when invoked, returns "I am a human."
  2. Create another class called child that inherits from Human and overrides the talk method and returns "I am a child."
  3. Create a male and female class that override talk and output "I am a Male." and "I am a Female."
  4. Change the child and human hierarchy to include male and female appropriately and output the proper string.

I completed tasks 1-3 but was stumped on question 4. I haven't really done much in my past work experience with inheritance and the question seemed kind of vague to me. I explained this to the employer and they seemed ok with it, but didn't tell me how it should have been done. Its been bugging me now and I'm wondering how it is done.

like image 499
jsmith Avatar asked Jun 20 '26 10:06

jsmith


1 Answers

It sounds as though they intend you to demonstrate that you understand the limitations of simple inheritance in this exercise. You can't model Humans with both age and sex represented by inheritors in the most simple model of inheritance. Consider the following:

  • Abstract Class Human inherited by both Child and Adult;
  • Abstract Class Human inherited by Male and Female

It becomes obvious that in this model, a human cannot be both Child and Female - or any other combination. Therefore the answer is that this simple model is inadequate and instead you should suggest alternative implementations which fulfil the requirements while using the established model as best you can.

I shall repeat what I've found myself saying often:

Objects should not attempt to represent reality. A good object model only need solve the problem at hand.

What I mean by this is that the Child/Adult and Male/Female exclusivity relationships should be modelled in the most appropriate way that solves the problem at hand. It doesn't matter if they aren't representative of reality. In your position I would attempt to suggest a variety of alternatives that would suit varying problems and explain why each is beneficial in that situation.

like image 185
Tom W Avatar answered Jun 23 '26 01:06

Tom W