The best example I know of is actors on a stage in a play - it also helps you avoid ending up in the inheritance tar pit.
Say we have the play Julius Caesar from William Shakespeare. You could implement it with a bunch of Actor classes
, from which e.g. the Calpurnia class
is derived. You could have multiple Calpurnia classes
(say for different actresses knowing the role of Calpurnia, each with different strength an weaknesses, but all of them able to play - more or less - properly their role).
When during a play of Julius Caesar Calpurnia says the line:
What mean you, Caesar? think you to walk forth?
You shall not stir out of your house to-day.
The instance of the Calpurnia class (= object
) sends a message
(= calls a method
on) an instance
of the Julius Caesar class. Which reacts according to the script (= algorithm
implemented in the called method) with the line:
The things that threaten'd me ne'er look'd but on my back; when they shall see
The face of Caesar, they are vanished.
The instance of the Calpurnia class though has no idea how the Caesar object creates this answer (= encapsulation
) and everyone is perfectly aware, that this is not the real Julius Caesar (or Calpurnia) standing on the stage, but actors representing reasonably romanticized versions of the historic persons (= abstraction
).
Another participating class in this scenario is the Spectator
class. They make heavy use of the fact, that all roles belong to the Actor
class and as such instances of them can be watched, listened too or applauded – or booed – irrespective of their concrete subclass (= polymorphism).
And of course there are thousands of different ways on how'd you be able to represent a play(house) in an object oriented fashion...