Download presentation
Presentation is loading. Please wait.
Published byAlison Loren Reed Modified over 9 years ago
1
Polymorphism and Inheritance
2
Overview Understanding Inheritance Designing an Inheritance Tree What does inheritance really help with Polymorphism
3
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
4
Understanding Inheritance Parent Animal Children Fish Dog
5
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
6
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
7
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
8
Polymorphism Polymorphism lets you link a super class object reference to a subclass object.
9
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(); }
10
More Polymorphism class Vet { public void giveShot(Animal a){ // Give animal a shot a.makeNoise(); }
11
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
12
Things to remember Inheritance is powerful but takes thought Using overriding makes using multiple object easier Using overloading gives more versatility to your methods
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.