Polymorphism and Inheritance
Overview Understanding Inheritance Designing an Inheritance Tree What does inheritance really help with Polymorphism
Understanding Inheritance Sometimes a class is to general and it is useful to have a more specific class for a purpose. This class can inherit functions and values from a parent Functions can be replaced with specialize versions
Understanding Inheritance Parent Animal Children Fish Dog
Designing an Inheritance Tree If you have multiple objects that need to inherit from other objects you need and inheritance tree Inheritance trees show which objects are sub classes to other objects They show what methods are overridden at each level
Overriding Methods When you have a class tree, the lowest method or most specific method is called first. wolf.roam calls from class Canine wolf.eat calls from class Wolf, not class Animal llama.eat calls from class Animal, not class Wolf
What does inheritance really help with In summary the concept of inheritance: Allows for reducing duplicate code Allows for the definition of a common protocol for a group of objects protocol (def.): The established code of procedure or behavior in any group, organization, or situation. Polymorphism
Polymorphism Polymorphism lets you link a super class object reference to a subclass object.
More Polymorphism Animal animals[4]; animals[0] = new Dog(); animals[1] = new Cat(); animals[2] = new Lion();..... for(int i = 0; i<4; i++){ animals[i].eat(); animals[i].roam(); }
More Polymorphism class Vet { public void giveShot(Animal a){ // Give animal a shot a.makeNoise(); }
Example polymorph.cpp We will create several animal classes that inherit from the base 'Animal' class We will look at how an 'Animal' pointer can point to any type of animal and still make it work
Things to remember Inheritance is powerful but takes thought Using overriding makes using multiple object easier Using overloading gives more versatility to your methods