polymorphism, virtual methods and interfaces version 1.1

35
Polymorphism, Virtual Methods and Interfaces Version 1.1

Upload: amos-henderson

Post on 19-Jan-2016

227 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Polymorphism, Virtual Methods and Interfaces Version 1.1

Polymorphism, Virtual Methods

and InterfacesVersion 1.1

Page 2: Polymorphism, Virtual Methods and Interfaces Version 1.1

Topics

Polymorphic VariablesOverriding MethodsVirtual MethodsAbstract MethodsAbstract ClassesThe Object ClassOverriding ToString MethodInterfaces

Page 3: Polymorphism, Virtual Methods and Interfaces Version 1.1

ObjectivesAt 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 classesCorrectly use polymorphism in a program* Store references to dynamically created objects in arrays of base class referencesOverride the ToString method in a classCreate and use an Interface

Page 4: Polymorphism, Virtual Methods and Interfaces Version 1.1

Polymorphic Variables

Consider the statement:

Creature cr1;

The declared type of the reference cr1 is Creature

However, cr1 can potentially hold a reference to anobject of a different type. In particular, it can hold a reference to an object of any class derived from Creature.

Page 5: Polymorphism, Virtual Methods and Interfaces Version 1.1

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);

Page 6: Polymorphism, Virtual Methods and Interfaces Version 1.1

Now what if I wrote a loop to compute the damagegenerated 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( ));}

Page 7: Polymorphism, Virtual Methods and Interfaces Version 1.1

Since myTeam is an array of Creature classreferences, we know that this code willcall the GetDamage( ) method in the Creature class. Can we write this code sothat it will call the correct GetDamagemethod for the type of object beingreferenced?

The answer is YES!

Page 8: Polymorphism, Virtual Methods and Interfaces Version 1.1

Creaturenamestrengthhitpoints

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.

Page 9: Polymorphism, Virtual Methods and Interfaces Version 1.1

Creaturenamestrengthhitpoints

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 .

Page 10: Polymorphism, Virtual Methods and Interfaces Version 1.1

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 invokeThe Dwarf’s GetDamage( )method

When i = 2 invokeThe Elf’s GetDamage( )method

When i = 3 invokeThe Fairy’sGetDamage( ) method

Page 11: Polymorphism, Virtual Methods and Interfaces Version 1.1

Virtual Methodsthe keyword virtual in a base class methodsays that we can over-ride this function in a derived class. When we use a base classreference to point to the object, and invokethe virtual function, the system will automatically find and execute the function defined in the derived class, not the onedefined in the base class!

Moreover, if we have many different derivedclasses, the system will find the correctfunction 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;}

Page 12: Polymorphism, Virtual Methods and Interfaces Version 1.1

Method Overridingthe keyword override in a derived class method

says that this method overrides the functionwith the same signature defined in the base class. When pointed to by a base class reference, thiswill cause the method defined in the derivedClass 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;}

Page 13: Polymorphism, Virtual Methods and Interfaces Version 1.1

Rules for Polymorphism

In the base class, the keyword virtual must precedeany method that you want to call using polymorphism.

In any derived class the signature must exactly matchthe signature of the method being over-ridden. If thesignature is different, the compiler considers it to bea different method, not an over-riding method. Usethe override keyword.

The actual implementation of the method in thederived class will be different than that in the baseclass.

The method is invoked through a base class referencethat references a derived class object.

Page 14: Polymorphism, Virtual Methods and Interfaces Version 1.1

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 inThe base class, we must define that method and the class as abstract.

Page 15: Polymorphism, Virtual Methods and Interfaces Version 1.1

Abstract Methodsthe keyword abstract in a base class methodsays that we must over-ride this function in any derived class. The class contains noimplementation.

public abstract int GetDamage( );

Page 16: Polymorphism, Virtual Methods and Interfaces Version 1.1

Abstract Classes

If a class contains at least one abstract method, theclass must be declared as abstract class.

You cannot create an object from an abstract class.

Abstract classes are truly an abstraction. The providea contract for all derived classes, defining the public methods that a derived class must implement.

Page 17: Polymorphism, Virtual Methods and Interfaces Version 1.1

abstract class Foo{ public: abstract void printMyData( ); protected: string myData;}

No body allowed in an abstract class!!

abstract forced on us by the compiler!

Page 18: Polymorphism, Virtual Methods and Interfaces Version 1.1

Abstract ClassesIf a class is abstract then it is impossible to create an object of that class.

Why?

Such classes are called abstract classes.

Page 19: Polymorphism, Virtual Methods and Interfaces Version 1.1

abstract public class Creature{ . . .

Use the abstract keyword at the beginning of an abstract class.

Page 20: Polymorphism, Virtual Methods and Interfaces Version 1.1

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 theToString() method.

Page 21: Polymorphism, Virtual Methods and Interfaces Version 1.1

One of the methods in the Object class that isoften over-ridden is the ToString Method. Bydefault the ToString method returns a stringobject containing the name of the class.

We often want the ToString method to return atextual representation of the class.

The following slides illustrate how to overridethe ToString method in the Creature classes.

Page 22: Polymorphism, Virtual Methods and Interfaces Version 1.1

The Format Method

The String class contains a method namedformat. The format method works just likethe Write method in the Console class. Datais formatted using format specifiers, but theresults are stored in a string object instead ofbeing written to the console.

Page 23: Polymorphism, Virtual Methods and Interfaces Version 1.1

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); }

Page 24: Polymorphism, Virtual Methods and Interfaces Version 1.1

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.

Page 25: Polymorphism, Virtual Methods and Interfaces Version 1.1

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.

Page 26: Polymorphism, Virtual Methods and Interfaces Version 1.1

Console.WriteLine(bestFairy.ToString( ) );

invokes

invokes

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); }

Page 27: Polymorphism, Virtual Methods and Interfaces Version 1.1

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!

Page 28: Polymorphism, Virtual Methods and Interfaces Version 1.1

Interfaces

What if you want to define a set of behaviors thatcould apply to many different classes . . . But you didnot want to define a whole new class to do this. Manyobject oriented languages provided the concept ofan interface to do this.

Page 29: Polymorphism, Virtual Methods and Interfaces Version 1.1

Interfaces

Let’s define a storable interface, and then add It to our creature classes.

Page 30: Polymorphism, Virtual Methods and Interfaces Version 1.1

public interface IStorable{ void Read(StreamReader input);

void Write(StreamWriter output);}

Use the keyword interface

Page 31: Polymorphism, Virtual Methods and Interfaces Version 1.1

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.

Page 32: Polymorphism, Virtual Methods and Interfaces Version 1.1

public class Creature : IStorable{ . . .

}

Use a colon and the name of the interfaceto be implemented – this is written justlike inheritance.

Page 33: Polymorphism, Virtual Methods and Interfaces Version 1.1

// Write Method to implement Istorable// Purpose: Writes a Creature object to diskpublic 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 diskpublic 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

Page 34: Polymorphism, Virtual Methods and Interfaces Version 1.1

Interface vs an Abstract Class

Abstract classes are used as the base class fora hierarchy of related classes. Derived classeshave an is-a relationship. For example, a Dwarfis-a Creature. A class can only inherit from a single base class. However, multiple derived classescan inherit from single base class.

Page 35: Polymorphism, Virtual Methods and Interfaces Version 1.1

Interface vs an Abstract Class

Interfaces are used to force behaviors on a hierarchy of related classes. Classes thatuse an interface have an implements relationshipto the interface. For example, Dwarf implements Istorable. A class inherit only one class; however, it may implement multiple interfaces.