Another useful technique in object orientated programming is Polymorphism, which allows you to impliment derived class methods through a base class pointer at run time.
This is useful for when you need to invoke the methods of objects stored in an array if the objects are not always of the same type. They must be related through inheritance however, and they have to be added as an inherited type.
{
public virtual void testMethod()
{
Console.WriteLine("I am a testClass");
}
}
Listing 1-1 Test base class
We can create a series of derived test classes which inherit from testClass and which also override the testMethod.
{
public override void testMethod()
{
Console.WriteLine("I am test 1");
}
}
class test2: testClass
{
public override void testMethod()
{
Console.WriteLine("I am test 2");
}
}
class test3 : testClass
{
public override void testMethod()
{
Console.WriteLine("I am test 3");
}
}
Now we will create an array of test objects and iterate through them using a foreach loop.
{
static void Main()
{
testClass[] testArray = new testClass[4];
testArray[0] = new test1();
testArray[1] = new test2();
testArray[2] = new test3();
testArray[3] = new test2();
foreach (testClass test in testArray)
{
test.testMethod();
}
}
}
When running the program the overridden testMethod of each object is called.
If your base class for the array were test2 instead of testClass, you would not be able to add test1 or test3 to the array. This technique only works if your objects are, or inherit from, the base class of the array. Why? Because test2 could have its own method defined which is not defined within test1 or test2, but a method defined in testClass is guaranteed to be inherited in test2.
No comments:
Post a Comment