Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.

So, what will be a nice, simple and concrete problem that is solved using Inheritance ?

share|improve this question

closed as not constructive by ChrisF Feb 17 '13 at 20:10

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
"the common example is often the mammals "? What do you mean? Can you provide a link, reference or quote for this? –  S.Lott Sep 14 '11 at 9:49
1  
3  
What would be the best real example to explain the usefulness of Inheritance = Bill Gates' kids trust fund? –  Martin Beckett Nov 22 '12 at 18:18

14 Answers 14

How about a hierarchy of algebraic expressions. Is good because it includes both inheritance and composition:

+--------------------+------------------------+
| Expression         |<------------------+    |
+--------------------+----------+        |    |
| + evaluate(): int  |<---+     |        |    |
+--------------------+    |     |        |    |
          ^               |     |        |    |
          |               |     |        |    |
   +--------------+  +---------------+  +-------------+  ...
   | Constant     |  | Negation      |  | Addition    |
   +--------------+  +---------------+  +-------------+
   | -value: int  |  |               |  |             |
   +--------------+  +---------------+  +-------------+
   | +evaluate()  |  | +evaluate()   |  | +evaluate() |
   | +toString()  |  | +toString()   |  | +toString() |
   +--------------+  +---------------+  +-------------+

   Addition(Constant(5), Negation(Addition(Constant(3),Constant(2))))
   (5 + -(3 + 2)) = 0

With the exception of the root expression Constant, all other expressions are both an Expression and contain one or more expressions.

share|improve this answer

Good example is the compare function in sorting:

template<class T>
class CompareInterface {
public:
   virtual bool Compare(T t1, T t2) const=0;
};
class FloatCompare : public CompareInterface<float> { };
class CompareImplementation : public FloatCompare {
public:
   bool Compare(float t1, float t2) const { return t1<t2; }
};
template<class T>
void Sort(T*array, int size, CompareInterface<T> &compare);

The only problem is the newbies too often think performance is more important than good code...

share|improve this answer

Chemistry Elements Example

This is another example popped out of my brain:

class Element_
{
    double atomicWeight; //Atomic weight of element
    double atomicNumber; // Atomic number of element
    String Properties;  // Properties of element
    //Others, if any
}


class Isotope extends Element_  // There can exist Isotopes of element
{
    double halflife;
   //Others if any

}
share|improve this answer
2  
Although atomicNumber can (should?) probably be integer... –  Andrew Dec 11 '12 at 6:04
    
I wouldn't use inheritance for that. isotope isn't a special case of Elemenet. I'd rather have an Element property on Isotope. –  CodesInChaos Feb 17 '13 at 20:42

Real-world examples almost always get it wrong because they give examples where there's always the possibility of something being both TypeA and TypeB but the single inheritance hierarchy of many languages don't allow that.

The more I program the more I get away from inheritance.

Even the word "inherit" is used improperly here. For instance, you inherit about 50% of your father's traits and 50% of your mother's traits. Really your DNA is a composition of half your father's DNA and half your mother's DNA. That's because biology actually favors composition over inheritance, and you should too.

Simply implementing interfaces, or even better, "duck typing", plus dependency injection, is a much better thing to be teaching people who are new to object-oriented programming.

share|improve this answer

This non-mammal, non-bird, non-fish example might help:

public abstract class Person {

    /* this contains thing all persons have, like name, gender, home addr, etc. */

    public Object getHomeAddr() { ... }

    public Person getName() { ... }

}

public class Employee extends Person{

    /* It adds things like date of contract, salary, position, etc */

    public Object getAccount() { ... }

}

public abstract class Patient extends Person {
    /* It adds things like medical history, etc */
}

Then

public static void main(String[] args) {

    /* you can send Xmas cards to patients and employees home addresses */

    List<Person> employeesAndPatients = Factory.getListOfEmployeesAndPatients();

    for (Person p: employeesAndPatients){
        sendXmasCard(p.getName(),p.getHomeAddr());
    }

    /* or you can proccess payment to employees */

    List<Employee> employees = Factory.getListOfEmployees();

    for (Employee e: employees){
        proccessPayment(e.getName(),e.getAccount());
    }       

}

NOTE: Just don't tell the secret: Person extends Mammal.

share|improve this answer
1  
Works until one of your employees is also a patient. –  Scott Whitlock Nov 22 '12 at 17:57
    
In this case, I think it makes more sense to declare Patient and Employee as interfaces instead of abstract classes. That gives you the flexibility of having Person implement multiple interfaces. –  Jin Kim Nov 22 '12 at 19:38
    
@JinKim - I totally agree, that's the better approach. –  Scott Whitlock Nov 22 '12 at 19:56
    
@JinKim They are not exclusive. You treat a person as an employee or a as patient at any given time, but not an the same time. Two interfaces is OK but then when what do you call a concrete class implementing both, EmployeePatient ? How many combinations will you have ? –  user61852 Nov 22 '12 at 22:57
    
You can call the concrete class whatever you want. If the code only expects to deal with Employees, you declare the reference as an Employee. (i.e. Employee employee = new Person(); ) If the code only expects to deals with a Patient, you declare the reference as a Patient. Rarely do you want to declare a reference directly as the concrete class. –  Jin Kim Nov 23 '12 at 18:40

I will use birds as example

like chicken , duck ,eagle

I will explain both have claws, pecks , and wings but their attributes are different.

Chickens cannot fly, cannot swim, can eat worms , can eat grains

Ducks cannot fly, can swim , can eat grains, cannot eat worms

Eagle can fly, cannot swim , can eat worms, cannot eat grains

share|improve this answer
4  
I once read that composition and interfaces are probably the best way to convey this type of concept i.e. fly, swim etc –  dreza Nov 22 '12 at 9:16

I am working with cameras at work. We have devices that connect to different models, so we have an abstract "camera class" and every model inherits from this class to support specific functionality of that camera. It's a real world example and not difficult to understand.

share|improve this answer
2  
This might break down if you have, e.g. a model that's both a Camera and a Phone (as we all do in our pockets now). Which base class should it inherit from? Or shouldn't it just implement both the ICamera and IPhone interfaces? (ha ha) –  Scott Whitlock Nov 22 '12 at 18:01
2  
@Scott: You can't implement the IPhone interface, or you'll get sued by Apple. –  Mason Wheeler Dec 11 '12 at 5:23

My real world example is a vehicle:

public class Vehicle
{
    public Vehicle(int doors, int wheels)
    {
        // I describe things that should be
        // established and "unchangeable" 
        // when the class is first "made"
        NumberOfDoors = doors;
        NumberOfWheels = wheels;
    }

    public void RollWindowsUp()
    {
        WindowsUp = true;
    }

    // I cover modifiers on properties to show
    // how to protect certain things from being
    // overridden
    public int NumberOfDoors { get; private set; }
    public int NumberOfWheels { get; private set; }

    public string Color { get; set; }
    public bool WindowsUp { get; set; }
    public int Speed { get; set; }
}

public class Car : Vehicle
{
    public Car : base(4, 4)
    {

    }
}

public class SemiTruck : Vehicle
{
    public SemiTruck : base(2, 18)
    {

    }
}

This example can get as detailed as you like, and there are all kinds of properties attached to vehicles to explain the use of any modifiers you might want to teach.

share|improve this answer
2  
I have always hated using vehicles as an example, as it does not get a new programmer any closer to understanding how inheritance can be used to improve code. Vehicles are immensely complicated machines that call to mind a lot of non-abstract ideas in the non-programmer's mind. Trying to describe this in code makes the average novice believe that there are a lot of details being left out of the example and gives the feeling that they are no closer to getting something to work. I say this from experience, as that is exactly how I felt when someone tried to use vehicles to explain it to me. –  Stargazer712 Sep 14 '11 at 14:32
    
@Stargazer712: I use vehicles primarily because they can be as complicated or as simple as you like. I leave it to the instructor's judgment to determine the level of his pupil. I explained basic OOP to my wife (who has zero programming experience) using the simple properties of a vehicle describing the common basics. All vehicles have doors, all vehicles have wheels, etc. The object example can't be blamed for a poor lesson plan. –  Joel Etherton Sep 14 '11 at 14:42
    
your wife wasn't trying to write code. I can very safely say that vehicle examples did nothing to help me understand inheritance. Whatever you use to describe inheritance, it must be complete and practical. The goal is not to describe it in such a way that a non-programmer can understand it. The goal is to describe it in such a way that a novice programmer can use it, and the only way to do that is to show the novice examples of how a professional programmer would use it. –  Stargazer712 Sep 14 '11 at 14:46
    
@Stargazer712: I would put your inability to initially understand inheritance on a poor lesson plan. I have also used vehicles to explain inheritance to the juniors I work with, and I've never had a problem with the concept coming across. In my opinion, if a lesson plan is thorough and properly constructed, a vehicle object is both complete and practical. 1 random guy on the internet is not going to change that in the face of the 30 or so interns and junior devs to whom I've taught OOP. If you don't like the vehicle, down-vote and move on. –  Joel Etherton Sep 14 '11 at 14:52
    
As you wish.... –  Stargazer712 Sep 14 '11 at 15:14

I'd just show them a real-life example. For instance, in most UI frameworks you derive from some kind of a "Dialog" or "Window" or "Control" class to make your own.

share|improve this answer

My real-world example is the domain model of a simple HR application. I tell that we can create a base class called Employee, because of course, managers are employees too.

public class Employee
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Code { get; set; }

    public string GetInsuranceHistory()
    {
        // Retrieving insurance history based on employee code.
    }
}

Then I explain that developers are employees, testers are employees, project managers are employees. Thus they all can inherit from the employee class.

share|improve this answer
1  
To show inheritance advantages, it might be interesting to also show how developers differ from employees. If there is no difference, then there's no need to create a Developer class at all. –  David Sep 14 '11 at 15:20
3  
Seems as though Employee could be an abstract class too. –  StuperUser Sep 14 '11 at 15:29
    
+1 this is the example most of my teachers used and I really liked it. it made complete sense and gave a real world example on how to use inheritance. –  David Peterman Sep 14 '11 at 17:48
16  
Except this never works in practice because there's always at least one person who needs to be both a Developer and a Tester. Another similar situation is a contact database where you have Customer and Supplier, but as anyone who has created such a system will tell you, there's always a case where a Company is both. That's why most of these examples lead you in the wrong direction. –  Scott Whitlock Nov 22 '12 at 17:47

There's nothing wrong with a purely academic example like mammals. I also like the rectangle/square example because it points out why real-world taxonomies don't always directly translate to the inheritance relationship you'd expect.

In my opinion, the most canonical every day example is a GUI toolkit. It's something everyone has used, but that beginners may not have reasoned about how they work under the hood. You can talk about what behaviors are common to all containers, all widgets, events, etc. without requiring detailed knowledge of any given implementation.

share|improve this answer
4  
+1 for GUI toolkits... and I also like the shapes example, with one Shape as the base with a minimal draw() and the descendant shapes with customized draw() s. –  yati sagade Sep 14 '11 at 17:58

Your typical rails-clone provides many practical examples: you have the (abstract) base model class, that encapsulates all data manipulation and you have the base controller class, that encapsulates all HTTP-communication.

share|improve this answer
    
Care to elaborate why this answer is bad? –  keppla Feb 20 '13 at 13:18

Remember

Every instance of an object is a concrete example of the usefulness of inheritance!

If you mean specifically class inheritance, now you are in the world of taxonomies, and those will vary drastically by the goals of the system using them. The animals/mammals example uses a common and hopefully familiar taxonomy from biology, but it is (as you mentioned) nearly useless for the vast majority of programming problems.

So try something universal: the notion of a Program. Every program starts, runs, and ends. Every program has a name, and optional command-line parameters. So a base Program class would be very useful, to start execution, grab and process the command-line arguments, run the main logic, and shut down gracefully.

Which is why so many object-oriented programming languages provide a Program class, or something that behaves exactly like a Program class.

share|improve this answer
    
So, you program a program that has many programs in it? :) In my experience, Programm Objects are almost always singletons that have no inheritance, so imho they are not the best example. –  keppla Sep 14 '11 at 9:24
    
@keppla: have you ever used Java or .NET? .NET has an explicit Program class, Java's is implicit. They are not singletons –  Steven A. Lowe Sep 14 '11 at 15:54
    
i used Java, around version 1.4.2. Back then, there was only static void main, so i guess it changed a little. What would be a typical reason to have more than one instance of the Programm class? –  keppla Sep 15 '11 at 6:28
    
@keppla: java's static void main implicitly makes the entry class represent the program. Every user that runs your program creates a new instance of it. At this moment, I have three instances of Google Chrome running, four Word documents, three Notepads, and two Windows Explorers. If they were all singletons I'd never be able to do that. –  Steven A. Lowe Sep 15 '11 at 8:57
1  
i think you stretching the definition a little. class Programm { public static void main(String[] args) { system.out.println('hello world'); }} is a minimal Java program. When i call it, there is no instance of Program. Program does not Inherit from anything. When i start 3 Processes (like you do with crhome), there may be 3 Programms, but in their individual areas of memory, there's still only one Program. Imho, singleton implies 'Only one Instance per Process', not per Machine. If so, it would be impossible to make singletons, nothing stops you from running any code twice. –  keppla Sep 15 '11 at 9:12

Encapsulate what varies ... show them a template method pattern, it demonstrates the usefulness of inheritance by putting common behaviour in a base class and encapsulating varying behaviour in subclasses.

UI controls and Streams are also a very good example for the usefulness of inheritance.

share|improve this answer
    
I think that factory would be a better example. –  Let_Me_Be Sep 14 '11 at 9:06
1  
@Let_Me_Be: I think the relationship between a factory and inheritance is too indirect in its nature. Sure, it produces concrete types and returns abstract/base types, but it could also return just an interface type! Imho that's not better than the classic animal example. –  Falcon Sep 14 '11 at 9:46
    
@Let_Me_Be: Also, an abstract factory is quite a complex example involving different inheritance hierarchies (one for the items, one for the factories). I think it's a good use of inheritance, but not a good and simple example. –  Falcon Sep 14 '11 at 9:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.