baldwin.jpg

Programming with XNA Game Studio

Runtime Polymorphism through Class Inheritance in C#

With runtime polymorphism, the selection of a method for execution is based on the actual type of the object whose reference is stored in a reference variable, and not on the type of the reference variable on which the method is called.

Published: January 26, 2010
Validated with Amaya

By Richard G. Baldwin

XNA Programming Notes # 0114


Preface

General

XNA Game Studio 3.1
Note that all references to XNA in this lesson are references to version 3.1 or later.

This tutorial lesson is part of a continuing series dedicated to programming with the XNA Game Studio. I am writing this series of lessons primarily for the benefit of students enrolled in an introductory XNA game programming course that I teach. However, everyone is welcome to study and benefit from the lessons.

An earlier lesson titled Getting Started (see Resources) provided information on how to get started programming with Microsoft's XNA Game Studio. (See Baldwin's XNA programming website in Resources.)

The three main characteristics of an object-oriented program

Object-oriented programs exhibit three main characteristics:

I have explained encapsulation, inheritance, and compile-time polymorphism in earlier lessons. I will continue my explanation of polymorphism in this lesson with an explanation of runtime polymorphism using method overriding and class inheritance. I will defer an explanation of polymorphism using interface inheritance until a future lesson.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the listings while you are reading about them.

Listings

Supplemental material

I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

General background information

What is polymorphism?

The meaning of the word polymorphism is something like one name, many forms.

How does C# implement polymorphism?

Polymorphism manifests itself in C# in the form of multiple methods having the same name.

In some cases, multiple methods have the same name, but different formal argument lists. This is polymorphism implemented using overloaded methods. I explained this form of polymorphism in an earlier lesson.

In other cases, multiple methods have the same name, same return type, and same formal argument list. This is method overriding, which is the main topic of this lesson.

The essence of runtime polymorphic behavior

Methods are called on references to objects. Typically, those references are stored in reference variables, or in the elements of a collection such as an array, stack, or queue.

The decision process

With runtime polymorphism based on method overriding, the decision regarding which version of a method will be executed is based on the actual type of the object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is called.

Stated differently, the type of the reference determines which methods can be called. The type of the object determines which method from that set of allowable methods will be called.

Late binding

The decision regarding which version of the method to call cannot be made at compile time. That decision must be deferred and made at runtime. This is sometimes referred to as late binding.

Operational description of runtime polymorphism

Here is an operational description of runtime polymorphism as implemented in C# through inheritance and method overriding:

This is runtime polymorphism.

Runtime polymorphism is very powerful

As you gain more experience with C#, you will learn that much of the power of OOP using C# is centered on runtime polymorphism using class inheritance, interfaces, and method overriding. (The use of interfaces for polymorphism will be discussed in a subsequent lesson.)

An important attribute of runtime polymorphism

This is worth repeating: The decision regarding which version of the method to execute is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is called.

Why is it called runtime polymorphism?

The reason that this type of polymorphism is often referred to as runtime polymorphism is because the decision regarding which version of the method to execute cannot be made until runtime. The decision cannot be made at compile time (as is the case with overloaded methods).

Why defer the decision?

The decision cannot be made at compile time because the compiler has no way of knowing (when the program is compiled) the actual type of the object whose reference will be stored in the reference variable.

For example, the type of the object might be the result of a choice made at runtime by a human user among several different possible choices.

Could be either type

For the situation described earlier, that object could just as easily be of type SuperClass as of type SubClass. In either case, it would be valid to assign the object's reference to the same superclass reference variable.

If the object were of the SuperClass type, then a call to the method named method on the reference would cause the version of the method defined in SuperClass, and not the version defined in SubClass, to be executed.

(One more time -- the version that is executed is determined by the type of the object and not by the type of the reference variable containing the reference to the object.)

Preview

From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in C#:

I covered method overloading as one form of polymorphism (compile-time polymorphism) in an earlier lesson.

I will begin the discussion of runtime polymorphism through method overriding and class inheritance in this lesson. I will cover interfaces in a future lesson.

Discussion and sample code

Let's take a look at a sample program that illustrates runtime polymorphism using class inheritance and overridden methods. The name of the program is Polymorph03. A complete listing of the program is shown in Listing 7 near the end of the lesson.

The class named A

I will discuss this program in fragments. Listing 1 shows the definition of a class named A, which extends the class named Object by default.

(Remember that any class that doesn't extend some other class automatically extends Object by default, and it is not necessary to show that explicitly.)

Listing 1. Class A.

using System;

class A {
  public virtual void m() {
    Console.WriteLine("m in class A");
  }//end method m()
}//end class A

The class named A defines a simple method named m.

A virtual method

Note that the method named m is declared to be virtual. This means that it is allowable to override this method in a subclass.

(If you come from a Java background, you will note that this is the reverse of the situation in Java. In Java, all methods are virtual by default unless they are declared to be final.)

Behavior of the method

The behavior of the method, as defined in the class named A, is to display a message indicating that it has been called, and that it is defined in the class named A.

This message will allow us to determine which version of the method is executed in each case discussed later.

The class named B

Listing 2 shows the definition of a class named B that extends the class named A.

Listing 2. Class B.

class B : A {
  public override void m() {
    Console.WriteLine("m in class B");
  }//end method m()
}//end 

The class named B overrides (redefines) the method named m, which it inherits from the class named A.

The override declaration

Note the use of the override declaration in Listing 2. In C#, if one method overrides another, it is necessary to declare that fact.

(Once again, if you come from a Java background, you will note that this is just the reverse of the situation in Java. In Java, a method whose name, return type, and formal argument list matches an inherited method will automatically override the inherited method.)

A compiler warning

If you fail to make the override declaration in Listing 2, you will get a compiler warning that reads something like the following:

warning CS0114: 'B.m()' hides inherited member 'A.m()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

Overriding versus hiding

I'm not going to get into a discussion of the difference between overriding and hiding in this lesson. Perhaps I will find the time to provide such a discussion in a future lesson.

Behavior of the overridden method

Like the inherited version of the method, the overridden version displays a message indicating that it has been called. However, the message is different from the message displayed by the inherited version discussed above. The overridden version tells us that it is defined in the class named B.

(According to the current jargon, the behavior of the overridden version of the method is appropriate for an object instantiated from the class named B.)

Again, this message will allow us to determine which version of the method is executed in each case discussed later.

The driver class

Listing 3 shows the beginning of the driver class named Polymorph03.

Listing 3. Beginning of the driver class.

public class Polymorph03 {
  public static void Main() {
    Object var = new B();
    //Following will compile and run
    ((B)var).m();

A new object of the class B

Note that the code in the Main method begins by instantiating a new object of the class named B, and assigning the object's reference to a reference variable of type Object.

(This is legal because an object's reference can be assigned to any reference variable whose type is a superclass of the class from which the object was instantiated. The class named Object is the superclass of all classes.)

Downcast and call the method

If you read the previous lesson, it will come as no surprise to you that the second statement in the Main method, which casts the reference down to type B and calls the method named m on it, will compile and execute successfully.

Which version was executed?

The execution of the method produces the following output on the computer screen:

m in class B

By examining the output, you can confirm that the version of the method that was overridden in the class named B is the version that was executed.

Why was this version executed?

This should also come as no surprise to you. The cast converts the type of the reference from type Object to type B.

You can always call a public method belonging to an object using a reference to the object whose type is the same as the class from which the object was instantiated.

Not runtime polymorphic behavior

Just for the record, the above invocation of the method does not constitute runtime polymorphism (in my opinion). I included that invocation of the method to serve as a backdrop for what follows.

(If this is runtime polymorphism, it is not a very significant example, because there was no requirement for the runtime system to decide between different methods having the same name. The runtime system simply executed a method belonging to an object using a reference of the same type as the object.)

This is runtime polymorphic behavior

However, the call to the method in Listing 4 does constitute runtime polymorphism.

Listing 4. This is runtime polymorphic behavior.

    //Following will also compile 
    // and run due to polymorphic
    // behavior.
    ((A)var).m();

The statement in Listing 4 casts the reference down to type A and calls the method named m on that reference.

The method output

Here is the punch line. Not only does the statement in Listing 4 compile and run successfully, it produces the following output, (which is exactly the same output as before):

m in class B

The same method was executed in both cases

Very important

It is very important to note that this output, (produced by casting the reference variable to type A instead of type B), is exactly the same as that produced by the earlier call to the method when the reference was cast to type B. This means that the same version of the method was executed in both cases.

This confirms that even though the type of the reference was converted to type A, (rather than type Object or type B), the overridden version of the method defined in class B was actually executed.

This is runtime polymorphic behavior in a nutshell.

The version of the method that was executed was based on the actual type of the object, B, and not on the type of the reference, A. This is an extremely powerful and useful concept.

Another invocation of the method

Now take a look at the statement in Listing 5. Will this statement compile and execute successfully? (Obviously, the answer to the question is given in Listing 5). If so, which version of the method will be executed?

Listing 5. A failed attempt.

    //Following will not compile
    //var.m();

Compiler error

The code in Listing 5 attempts, unsuccessfully, to call the method named m using the reference variable named var, which is of type Object. The result is a compiler error, which reads something like the following:

error CS0117: 'object' does not contain a definition for 'm'

Some important rules

The Object class does not define a method named m. Therefore, the overridden method named m in the class named B is not an overridden version of a method that is defined in the class named Object.

Necessary, but not sufficient

Runtime polymorphism based on class inheritance requires that the type of the reference variable be a superclass of the class from which the object (on which the method will be called) is instantiated.

(At least this requirement is true if a significant decision among methods is to be made.)

However, while necessary, that is not sufficient to ensure runtime polymorphic behavior.

Must define or inherit the method

The type of the reference variable must also be the name of a class that either defines or inherits a version of the method that will ultimately be called on the object.

This method is not defined in the Object class

Since the class named Object does not define (or inherit) the method named m, a reference of type Object does not qualify as a participant in runtime polymorphic behavior in this case. The attempt to use it as a participant results in the compiler error given above.

One additional scenario

Before leaving this topic, let's look at one additional scenario to help you distinguish what is, and what is not, runtime polymorphism. Consider the code shown in Listing 6.

Listing 6. Not polymorphic behavior.

    //Instantiate obj of class A
    var = new A();
    //Call the method on it
    ((A)var).m();

    // Pause until the user presses any key.
    Console.ReadKey();
  }//end Main
}//end class Polymorph03

A new object of type A

The code in Listing 6 instantiates a new object of the class named A, and stores the object's reference in the original reference variable named var of type Object.

(As a side note, this overwrites the previous contents of the reference variable with a new reference and causes the object whose reference was previously stored there to become eligible for garbage collection.)

Downcast and call the method

Then the code in Listing 6 casts the reference down to type A, (the type of the object to which the reference refers), and calls the method named m on the downcast reference.

The output

As you would probably predict, this produces the following output on the computer screen:

m in class A

In this case, the version of the method defined in the class named A, (not the version defined in B) was executed.

Not polymorphic behavior

Once again, in my view, this is not runtime polymorphic behavior (at least it isn't a very useful form of polymorphic behavior). This code simply converts the type of the reference from type Object to the type of the class from which the object was instantiated, and calls one of its methods. Nothing special takes place regarding a selection among different versions of the method.

Once again, what is runtime polymorphism?

As I have discussed in this lesson, runtime polymorphic behavior based on inheritance occurs when

More than you ever wanted to hear

And that is probably more than you ever wanted to hear about runtime polymorphism based on inheritance.

A future lesson will discuss runtime polymorphism based on the C# interface. From a practical viewpoint, you will find the rules to be similar but somewhat different in the case of the C# interface.

Run the program

I encourage you to copy the code from Listing 7.  Use that code to to create a C# console project..  Compile and run the project.  Experiment with the code, making changes, and observing the results of your changes.  Make certain that you can explain why your changes behave as they do. 

Summary

Polymorphism manifests itself in C# in the form of multiple methods having the same name.

From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in C#:

This lesson discusses method overriding through class inheritance.

With runtime polymorphism based on method overriding, the decision regarding which version of a method will be executed is based on the actual type of object whose reference is stored in a reference variable, and not on the type of the reference variable on which the method is called.

The decision regarding which version of the method to call cannot be made at compile time. That decision must be deferred and made at runtime. This is sometimes referred to as late binding.

Complete program listing

A complete listing of the XNA program discussed in this lesson is provided in Listing 7.

Listing 7. Project Polymorph03.

/*Project Polymorph03
Copyright 2009, R.G.Baldwin

This program illustrates downcasting
and polymorphic behavior

Program output is:
  
m in class B
m in class B
m in class A
*********************************************************/
using System;

class A {
  public virtual void m() {
    Console.WriteLine("m in class A");
  }//end method m()
}//end class A
//======================================================//

class B : A {
  public override void m() {
    Console.WriteLine("m in class B");
  }//end method m()
}//end class B
//======================================================//

public class Polymorph03 {
  public static void Main() {
    Object var = new B();
    //Following will compile and run
    ((B)var).m();
    //Following will also compile 
    // and run due to polymorphic
    // behavior.
    ((A)var).m();
    //Following will not compile
    //var.m();
    //Instantiate obj of class A
    var = new A();
    //Call the method on it
    ((A)var).m();

    // Pause until the user presses any key.
    Console.ReadKey();
  }//end Main
}//end class Polymorph03


Copyright

Copyright 2009, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is object-oriented programming using Java and other OOP languages.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-