<< Chapter < Page | Chapter >> Page > |
However, while necessary, that is not sufficient to ensure runtime polymorphic behavior.
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 becalled on the object.
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.
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 codeshown 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
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 .
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.
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.
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 ofits methods. Nothing special takes place regarding a selection among different versions of the method.
As I have discussed in this module, runtime polymorphic behavior based on inheritance occurs when
And that is probably more than you ever wanted to hear about runtime polymorphism based on inheritance.
A future module will discuss runtime polymorphism based on the C# interface. From a practical viewpoint, you will find the rules to be similar but somewhatdifferent in the case of the C# interface.
I encourage you to copy the code from Listing 7 . Use that code 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.
Notification Switch
Would you like to follow the 'Xna game studio' conversation and receive update notifications?