<< Chapter < Page | Chapter >> Page > |
Upon examination of the program, you will see that the class named A extends the class named Object . You will also see that the class named B extends the class named A .
The class named Polymorph01 is a driver class whose Main method exercises the methods defined in the classes named A and B .
Once again, this program is not intended to correspond to any particular real-world scenario. Rather, it is a very simple program designed specificallyto illustrate method overloading.
As usual, I will discuss this program in fragments. A complete listing is provided in Listing 4 near the end of the module.
The code in Listing 1 defines the class named A , which explicitly extends Object .
Listing 1 . Class A from the project named Polymorph01.
using System;
class A : Object {public void m() {
Console.WriteLine("m()");}//end method m()
}//end class A
Recall that explicitly extending Object is not required (but it also doesn't hurt anything).
The class named A would extend the class named Object by default unless the class named A explicitly extends some other class.
The code in Listing 1 defines a method named m() . Note that this version of the method has an empty argument list (it doesn't receive anyparameters when it is executed). The behavior of the method is simply to display a message indicating that it is executing.
Listing 2 contains the definition for the class named B . This class extends the class named A and inherits the method named m defined in the class named A .
Listing 2 . Class B from the project named Polymorph01.
class B : A {
public void m(int x) {Console.WriteLine("m(int x)");
}//end method m(int x)//---------------------------------//
public void m(String y) {Console.WriteLine("m(String y)");
}//end method m(String y)}//end class B
In addition to the inherited method named m , the class named B defines two additional overloaded versions of the method named m :
Note that each of these versions of the method receives a single parameter and the type of the parameter is different in each case.
As with the version of the method having the same name defined in the class named A , the behavior of each of these two methods is simply to display a message indicating that it is executing.
Listing 3 contains the definition of the driver class named Polymorph01 .
Listing 3 . Class Polymorph01 from the project named Polymorph01.
public class Polymorph01 {
public static void Main() {B var = new B();
var.m();var.m(3);
var.m("String");//Pause until the user presses a key.
Console.ReadKey();}//end Main
}//end class Polymorph01
The code in the Main method
Notification Switch
Would you like to follow the 'Xna game studio' conversation and receive update notifications?