Download presentation
Presentation is loading. Please wait.
Published byAmos Henderson Modified over 9 years ago
1
Polymorphism, Virtual Methods and Interfaces Version 1.1
2
Topics Polymorphic Variables Overriding Methods Virtual Methods Abstract Methods Abstract Classes The Object Class Overriding ToString Method Interfaces
3
Objectives At the completion of this module, students should be able to: Design classes that enable polymorphism * Properly use inheritance * Include virtual methods * Use abstract methods and abstract classes Correctly use polymorphism in a program * Store references to dynamically created objects in arrays of base class references Override the ToString method in a class Create and use an Interface
4
Polymorphic Variables Consider the statement: Creature cr1; The declared type of the reference cr1 is Creature However, cr1 can potentially hold a reference to an object of a different type. In particular, it can hold a reference to an object of any class derived from Creature.
5
So I could define an array of Creature objects like this: Const int TEAM = 3; Creature[ ] myTeam = new Creature[TEAM]; myTeam[0] = new Dwarf(“Bulgar”, 100, 300, 4); myTeam[1] = new Elf(“Razel”, 200, 200, 12); myTeam[2] = new Fairy(“Gina”, 250, 150, 6, 3);
6
Now what if I wrote a loop to compute the damage generated by each of the creatures on my team: Const int TEAM = 3; Creature[ ] myTeam = new Creature[TEAM]; myTeam[0] = new Dwarf(“Bulgar”, 100, 300, 4); myTeam[1] = new Elf(“Razel”, 200, 200, 12); myTeam[2] = new Fairy(“Gina”, 250, 150, 6, 3); for (int i = 0; i < TEAM; i++) { Console.WriteLine(“Damage Points = {0}”, myTeam[ i ].GetDamage( )); }
7
Since myTeam is an array of Creature class references, we know that this code will call the GetDamage( ) method in the Creature class. Can we write this code so that it will call the correct GetDamage method for the type of object being referenced? The answer is YES!
8
Creature name strength hitpoints Dwarf Method Overriding public virtual int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; } public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); if (rgen.Next(1, 101) < 25) damage = damage + 50; return damage; } * Make the GetDamage in the Creature class virtual.
9
Creature name strength hitpoints Dwarf Method Overriding public virtual int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; } public override int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); if (rgen.Next(1, 101) < 25) damage = damage + 50; return damage; } * Then make the GetDamage method in each derived class override the GetDamage method in the base class.
10
Const int TEAM = 3; Creature[ ] myTeam = new Creature[TEAM]; myTeam[0] = new Dwarf(“Bulgar”, 100, 300, 4); myTeam[1] = new Elf(“Razel”, 200, 200, 12); myTeam[2] = new Fairy(“Gina”, 250, 150, 6, 3); for (int i = 0; i < TEAM; i++) { Console.WriteLine(“Damage Points = {0}”, myTeam[ i ].GetDamage( )); When i = 1 invoke The Dwarf’s GetDamage( ) method When i = 2 invoke The Elf’s GetDamage( ) method When i = 3 invoke The Fairy’s GetDamage( ) method
11
Virtual Methods the keyword virtual in a base class method says that we can over-ride this function in a derived class. When we use a base class reference to point to the object, and invoke the virtual function, the system will automatically find and execute the function defined in the derived class, not the one defined in the base class! Moreover, if we have many different derived classes, the system will find the correct function for the object that the reference points to. This is called late binding, or dynamic binding. public virtual int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; }
12
Method Overriding the keyword override in a derived class method says that this method overrides the function with the same signature defined in the base class. When pointed to by a base class reference, this will cause the method defined in the derived Class to be executed! public override int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); if (rgen.Next(1, 101) < 25) damage = damage + 50; return damage; }
13
Rules for Polymorphism In the base class, the keyword virtual must precede any method that you want to call using polymorphism. In any derived class the signature must exactly match the signature of the method being over-ridden. If the signature is different, the compiler considers it to be a different method, not an over-riding method. Use the override keyword. The actual implementation of the method in the derived class will be different than that in the base class. The method is invoked through a base class reference that references a derived class object.
14
Abstract Methods In the previous example, we over-rode the GetDamage( ) method in all of the classes derived from the Creature class. However, there was nothing in the structure of the code that forced us to do this. To force a derived class to override a virtual method in The base class, we must define that method and the class as abstract.
15
Abstract Methods the keyword abstract in a base class method says that we must over-ride this function in any derived class. The class contains no implementation. public abstract int GetDamage( );
16
Abstract Classes If a class contains at least one abstract method, the class must be declared as abstract class. You cannot create an object from an abstract class. Abstract classes are truly an abstraction. The provide a contract for all derived classes, defining the public methods that a derived class must implement.
17
abstract class Foo { public: abstract void printMyData( ); protected: string myData; } No body allowed in an abstract class!! abstract forced on us by the compiler!
18
Abstract Classes If a class is abstract then it is impossible to create an object of that class. Why? Such classes are called abstract classes.
19
abstract public class Creature {... Use the abstract keyword at the beginning of an abstract class.
20
The Object Class Every class in C# must implicitly or explicitly derive from the base class Object. The Object class contains a number of virtual methods that derived Classes often override. The one most often used is the ToString() method.
21
One of the methods in the Object class that is often over-ridden is the ToString Method. By default the ToString method returns a string object containing the name of the class. We often want the ToString method to return a textual representation of the class. The following slides illustrate how to override the ToString method in the Creature classes.
22
The Format Method The String class contains a method named format. The format method works just like the Write method in the Console class. Data is formatted using format specifiers, but the results are stored in a string object instead of being written to the console.
23
The ToString( ) function in the Base class: public override string ToString( ) { return string.Format("My name is {0},\nmy strength is {1},\nmy hitpoint value is {2}", name, strength, hitPoints); }
24
The ToString( ) function in the MagicalCreature class: public override string ToString( ) { return base.ToString( ) + string.Format(“\nI am a Magical Creature, and I have {0} spells ”, spells); } base.ToString( ) calls the ToString method in the Creature class.
25
The ToString( ) function in the Fairy class: public override string toString( ) { return base.ToString( ) + string.Format( “\nI am a fairy, and my speed is {0}.”, speed); } base.ToString( ) calls the ToString method in the MagicalCreature class.
26
Console.WriteLine(bestFairy.ToString( ) ); invokes public override string toString( ) { return base.ToString( ) + string.Format( “\nI am a fairy, and my speed is {0}.”, speed); } public override string ToString( ) { return base.ToString( ) + string.Format(“\nI am a Magical Creature, and I have {0} spells ”, spells); } public override string ToString( ) { return string.Format("My name is {0},\nmy strength is {1},\nmy hitpoint value is {2}", name, strength, hitPoints); }
27
Note that you can now write the following: Fairy f1 = new Fairy(“Greenleaf”, 200, 50, 3,3); Console.WriteLine(f1); This calls the ToString method in the Fairy class!
28
Interfaces What if you want to define a set of behaviors that could apply to many different classes... But you did not want to define a whole new class to do this. Many object oriented languages provided the concept of an interface to do this.
29
Interfaces Let’s define a storable interface, and then add It to our creature classes.
30
public interface IStorable { void Read(StreamReader input); void Write(StreamWriter output); } Use the keyword interface
31
public interface IStorable { void Read(StreamReader input); void Write(StreamWriter output); } An interface can contain methods and properties. Methods are public by default. Methods have no implementation.
32
public class Creature : IStorable {... } Use a colon and the name of the interface to be implemented – this is written just like inheritance.
33
// Write Method to implement Istorable // Purpose: Writes a Creature object to disk public virtual void Write(StreamWriter output) { output.WriteLine(name); output.WriteLine(strength); output.WriteLine(hitPoints); } // Read Method to implement Istorable // Purpose: Reads a Creature object from disk public virtual void Read(StreamReader input) { name = input.ReadLine(); strength = int.Parse(input.ReadLine() ); hitPoints = int.Parse(input.ReadLine( ) ); } Write the code to implement the methods
34
Interface vs an Abstract Class Abstract classes are used as the base class for a hierarchy of related classes. Derived classes have an is-a relationship. For example, a Dwarf is-a Creature. A class can only inherit from a single base class. However, multiple derived classes can inherit from single base class.
35
Interface vs an Abstract Class Interfaces are used to force behaviors on a hierarchy of related classes. Classes that use an interface have an implements relationship to the interface. For example, Dwarf implements Istorable. A class inherit only one class; however, it may implement multiple interfaces.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.