I'm writing documentation for an object-oriented language, and I wonder what kind of classes would be a good example for inheritance.
Some common examples:
class Person {
}
class Employee extends Person {
}
Currently my favorite, but I don't like Person->Employee because 'Employee' does not exactly look like fun.
class Bicycle {
}
class MountainBike extends Bicycle {
}
I found this in some Java tutorial, but it's not really obvious what attributes a bike should have.
class Animal {
}
class Bird extends Animal {
}
Same as the bicycle.
class A {
}
class B extends A {
}
Too abstract. The main problem is that such a class will need even more abstract attributes and methods.
Does anyone have a better example for a simple class hierarchy?
I like the vehicles example, as it allows for a relatively clean extension to include interfaces into the discussion (IAutomaticGearbox, anyone?)
Inheritance can be complex. Let's start with the simplest of 'em all -- behavior inheritance. Here you are inheriting behavior only and no state. E.g: Both Person and Animal are Animate objects which exhibit an IsAlive behavior. To use your example:
I wrote this using C++ syntax, if you have problems understanding any of it, just say so!
Example:
The "Everything derives from Object" approach.
Dog --> Animal --> Living thing --> Object
A Dog is an Animal, which is a Living thing, which in turn is an Object.
You can find good examples of class inheritance in design-patterns.
Abstract_factory_pattern : Provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete class
Template_method_pattern: It is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses.
Decorator_pattern: It is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class
Refer to below posts for real world examples:
When to Use the Decorator Pattern?
Template design pattern in JDK, could not find a method defining set of methods to be executed in order
Auto Parts can be interesting for example you might have
The best example that i have came across (and read in many books) is the one that uses Shape.
The best thing about this is that you can very easily explain all the concepts (including the tough ones ) related to OOPs like Class,Object,Inheritance,Abstraction,Encapsulation,Polymorphism,etc to any programmer irrelevant of his experience.