Personal notes on software development.
For Java technologies check my dedicated site

Pages

Example 1.1:

class Program
{
    static void Main(string[] args)
    {
        MySubClass testObject = new MySubClass();
        testObject.OverrideTest();            
    }
}



class MyBaseClass
{
    public MySubClass()
    {           
        Console.WriteLine("Created BaseClass");       
    }

    public void OverrideTest(){
        Console.WriteLine("Base method used");
    }
}



class MySubClass : MyBaseClass
{
    public MySubClass()
    {           
        Console.WriteLine("Created SubClass");       
    }

    public void OverrideTest()
    {
        Console.WriteLine("Subclass method used");
    }
}
/*OUTPUT:
Created BaseClass
Created SubClass
Base method used
*/

Example 1.2:
Lets add a OverrideTest() to the subclass, leaving the other classes like before.
class MySubClass : MyBaseClass
{
    public MySubClass()
    {           
        Console.WriteLine("Created SubClass");       
    }

    public override void OverrideTest()
    {
        Console.WriteLine("Subclass method used");
    }
}
/*OUTPUT:
Created BaseClass
Created SubClass
Subclass method used
*/
This time the subclass method is used.


Example 1.3:
Lets include a creation of a second subclass.
The second one will be called through a cast to the base class.
class Program
{
    static void Main(string[] args)
    {
        MySubClass testObject = new MySubClass();
        testObject.OverrideTest();  

        Console.WriteLine("\nSecond object:");
        MySubClass testObject2 = new MySubClass();
        ((MyBaseClass)testObject2).OverrideTest();
    }
}
/*OUTPUT
Created BaseClass
Created SubClass
Subclass method used

Second object:
Created BaseClass
Created SubClass
Base method used
*/

Example 1.4:
If we make the Base class method "virtual":
public virtual void OverrideTest()
{
    (...)
}
The output is the same has the previous output.

Example 1.5:
But then if we mark the subclass method has override:
public virtual void OverrideTest(){
        Console.WriteLine("Base method used");
    }
/*OUTPUT:
Created BaseClass
Created SubClass
Subclass method used

Second object:
Created BaseClass
Created SubClass
Subclass method used
*/
The SubClass method is used in both cases.
Since we marked the base class as virtual and the subclass as override, the compiler knows it should use the subclass method instead of the base class one.
This is very useful, for example, when we have different objects in a List and want to use them polymorphic-ally (each object should use its specialized method). Example: A List of Mammal objects were Cat and Dog should use their own specialized versions of the method.

No comments:

Post a Comment