Wednesday, July 4, 2007

Override and New Keywords (C#.NET)

Override and New Keywords (C#.NET) :
 
// Define the base class
class Car
{
    public virtual void DescribeCar()
    {
        System.Console.WriteLine("Four wheels and an engine.");
    }
}
 
// Define the derived classes
class ConvertibleCar : Car
{
    public new virtual void DescribeCar()
    {
        base.DescribeCar();
        System.Console.WriteLine("A roof that opens up.");
    }
}
 
class Minivan : Car
{
    public override void DescribeCar()
    {
        base.DescribeCar();
        System.Console.WriteLine("Carries seven people.");
    }
}
 
public static void TestCars1()
{
    Car car1 = new Car();
    car1.DescribeCar();
    System.Console.WriteLine("----------");
 
    ConvertibleCar car2 = new ConvertibleCar();
    car2.DescribeCar();
    System.Console.WriteLine("----------");
 
    Minivan car3 = new Minivan();
    car3.DescribeCar();
    System.Console.WriteLine("----------");
}
 
Output:
Four wheels and an engine.
 
----------
 
Four wheels and an engine.
 
A roof that opens up.
 
----------
 
Four wheels and an engine.
 
Carries seven people.
 
----------
 

Test 2:
public static void TestCars2()
{
    Car[] cars = new Car[3];
    cars[0] = new Car();
    cars[1] = new ConvertibleCar();
    cars[2] = new Minivan();
 
foreach (Car vehicle in cars)
{
    System.Console.WriteLine("Car object: " + vehicle.GetType());
    vehicle.DescribeCar();
    System.Console.WriteLine("----------");
}
 
}
 
The output from this loop is as follows:
 
Car object: YourApplication.Car
 
Four wheels and an engine.
 
----------
 
Car object: YourApplication.ConvertibleCar
 
Four wheels and an engine.
 
----------
 
Car object: YourApplication.Minivan
 
Four wheels and an engine.
 
Carries seven people.
 

----------------------------------------------------------------------------------------------------------------
Notice how the ConvertibleCar description is not what you might expect. As the new keyword was used to define this method, the derived class method is not called—the base class method is called instead. The Minivan object correctly calls the overridden method, producing the results we expected.
 
If you want to enforce a rule that all classes derived from Car must implement the DescribeCar method, you should create a new base class that defines the method DescribeCar as abstract. An abstract method does not contain any code, only the method signature. Any classes derived from this base class must provide an implementation of DescribeCar.
---------------------------------------------------------------------------------------------------------
Reference: MSDN Library
http://msdn2.microsoft.com/en-us/library/ms173153(VS.80).aspx
 
 

No comments: