From within the derived class that has an override method, you still can access the overridden base method that has the same name by using the base keyword. For example, if you have a virtual method MyMethod() and an override method on a derived class, you can access the virtual method from the derived class by using the call base.MyMethod(). Listing 5.53 illustrates this concept.
Listing 5.53: Polymorphism.cs, Polymorphism Example
// notice the comments/warnings in the Main
// calling overridden methods from the base class
using System;
class TestClass
{
public class Square
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double Area()
{
return x * x;
}
}
class Cube : Square
{
// Constructor:
public Cube(double x)
: base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (6 * (base.Area()));
}
}
public static void MyFormat(IFormattable value, string formatString)
{
Console.WriteLine("{0}\t{1}", formatString, value.ToString(formatString,
null));
}
public static void Main()
{
double x = 5.2;
Square s = new Square(x);
Square c = new Cube(x); // This is OK, polymorphic
// a base reference can refer to the derived object
Console.Write("Area of Square = ");
MyFormat(s.Area(), "n");
Console.Write("Area of Cube = ");
MyFormat(c.Area(), "n");
// ERROR: Cube q = new Square(x);
// Cannot implicitly convert type 'TestClass.Square' to 'TestClass.Cube'
Cube q1 = (Cube)c; // This is OK, polymorphic
Console.Write("Area of Cube again = ");
MyFormat(q1.Area(), "n");
Console.ReadLine();
// try uncommenting the following line and see if it works
// Cube q2 = (Cube) new Square(x);
// This compiles but is this OK? NO!
//Runtime Exception occurs here: System.InvalidCastException:
//An exception of type System.InvalidCastException was thrown.
// A derived reference should not be transformed from base object,
// since the orphaned parts may occur in the derived.
// Cube constructors those may be necessary had not worked up to now for q2.
// C# compiles code but gives an exception during runtime
}
}
Figure 5.13 contains the resulting screen output.

Figure 5.13: Screen Output Generated from Listing 5.53
No comments:
Post a Comment