Friday, June 19, 2009

OOPS - Polymorphism

Polymorphism
The ability for an object to represent more than one type is called polymorphism.
When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member.
Replacing a member of a base class with a new derived member requires the
new keyword. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. The new keyword is placed before the return type of a class member that is being replaced. For example:
public class BaseClass
{
public void DoWork()
{ }
public int WorkField;
public int WorkProperty
{ get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork()
{ }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class. For example:
DerivedClass B = new DerivedClass();B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;A.DoWork(); // Calls the old method.
In order for an instance of a derived class to completely take over a class member from a base class, the base class has to declare that member as virtual. This is accomplished by adding the virtual keyword before the return type of the member. A derived class then has the option of using the override keyword, instead of new, to replace the base class implementation with its own.
For example:
public class BaseClass
{
public virtual void DoWork()
{ }
public virtual int WorkProperty
{ get { return 0; } }
}
public class DerivedClass : BaseClass
{
public override void DoWork()
{ }
public override int WorkProperty
{ get { return 0; } }
}
Fields cannot be virtual; only methods, properties, events and indexers can be virtual. When a derived class overrides a virtual member, that member is called even when an instance of that class is being accessed as an instance of the base class. For example:
C#

DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.

BaseClass A = (BaseClass)B;
A.DoWork(); // Also calls the new method.
Virtual methods and properties allow you to plan ahead for future expansion. Because a virtual member is called regardless of which type the caller is using, it gives derived classes the option to completely change the apparent behavior of the base class.
Virtual members remain virtual indefinitely, no matter how many classes have been declared between the class that originally declared the virtual member. If class A declares a virtual member, and class B derives from A, and class C derives from B, class C inherits the virtual member, and has the option to override it, regardless of whether class B declared an override for that member. For example:
public class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
C#
public class C : B
{
public override void DoWork() { }
}

A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the
sealed keyword before the override keyword in the class member declaration. For example:
C#
public class C : B
{
public sealed override void DoWork() { }
}
In the previous example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes using the new keyword, as the following example shows:
C#
public class D : C
{
public new void DoWork() { }
}
In this case, if DoWork is called on D using a variable of type D, the new DoWork is called. If a variable of type C, B, or A is used to access an instance of D, a call to DoWork will follow the rules of virtual inheritance, routing those calls to the implementation of DoWork on class C.
A derived class that has replaced or overridden a method or property can still access the method or property on the base class using the base keyword. For example:
C#
public class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
C#
public class C : B
{
public override void DoWork()
{
// Call DoWork on B to get B's behavior:
base.DoWork();

// DoWork behavior specific to C goes here:
// ...
}
}


Versioning with the Override and New Keywords (C# Programming Guide):
The C# language is designed so that versioning between
base and derived classes in different libraries can evolve and maintain backwards compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is completely supported by C# and does not lead to unexpected behavior. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that simply hides a similarly named inherited method.
C# allows derived classes to contain methods with the same name as base class methods.
The base class method must be defined
virtual.
If the method in the derived class is not preceded by
new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.
If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method rather than the base class method.
The base class method can be called from within the derived class using the base keyword.
The override, virtual, and new keywords can also be applied to properties, indexers, and events.
By default, C# methods are not virtual — if a method is declared as virtual, any class inheriting the method can implement its own version. To make a method virtual, the virtual modifier is used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. For more information, see
Compiler Warning CS0108.
To demonstrate this in practice, assume for a moment that Company A has created a class entitled GraphicsClass, which your program uses. GraphicsClass looks like this:
C#

class GraphicsClass
{
public virtual void DrawLine() { }
public virtual void DrawPoint() { }
}
Your company uses this class, and you use it to derive your own class, adding a new method:
C#
class YourDerivedGraphicsClass : GraphicsClass
{
public void DrawRectangle() { }
}
Your application is used without problems, until Company A releases a new version of GraphicsClass, which looks like this:
C#
class GraphicsClass
{
public virtual void DrawLine() { }
public virtual void DrawPoint() { }
public virtual void DrawRectangle() { }
}
The new version of GraphicsClass now contains a method entitled DrawRectangle. Initially, nothing happens. The new version is still binary compatible with the old — any software you have deployed will continue to work, even if the new class is installed on those computer systems. Any existing calls to the method DrawRectangle will continue to reference your version, in your derived class.
However, once you recompile your application using the new version of GraphicsClass, you will receive a warning from the compiler. For more information, see
Compiler Warning CS0108.
This warning informs you that you need to consider how you want your DrawRectangle method to behave in your application.
If you want your method to override the new base class method, use the override keyword, like this:
C#
class YourDerivedGraphicsClass : GraphicsClass
{
public override void DrawRectangle() { }
}
The override keyword makes sure that any objects derived from YourDerivedGraphicsClass will use the derived class version of DrawRectangle. Objects derived from YourDerivedGraphicsClass can still access the base class version of DrawRectangle using the base keyword, like this:
C#
base.DrawRectangle();
If you do not want your method to override the new base class method, the following considerations apply.To avoid confusion between the two methods, you can rename your method. This can be time-consuming and error-prone, and simply not practical in some situations. However, if your project is relatively small, you can use Visual Studio's Refactoring options to rename the method. For more information, see
Refactoring Classes and Types.
Alternatively, you can prevent the warning by using the keyword new in your derived class definition, like this:
C#
class YourDerivedGraphicsClass : GraphicsClass
{
public new void DrawRectangle() { }
}
Using the new keyword tells the compiler that your definition hides the definition contained in the base class. This is the default behavior.
Override and Method Selection
When a method is named on a class, the C# compiler selects the best method to call if more than one method is compatible with the call, such as when there are two methods with the same name, and parameters that are compatible with the parameter passed. The following methods would be compatible:
C#
public class Derived : Base
{
public override void DoWork(int param) { }
public void DoWork(double param) { }
}
When DoWork is called on an instance of Derived, the C# compiler will first try to make the call compatible with the versions of DoWork declared originally on Derived. Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters. For example:
C#
int val = 5;
Derived d = new Derived();
d.DoWork(val); // Calls DoWork(double).
Because the variable val can be converted to a double implicitly, the C# compiler calls DoWork(double) instead of DoWork(int). There are two ways to avoid this. First, avoid declaring new methods with the same name as virtual methods. Second, you can instruct the C# compiler to call the virtual method by making it search the base class method list by casting the instance of Derived to Base. Because the method is virtual, the implementation of DoWork(int) on Derived will be called. For example:
C#
((Base)d).DoWork(val); // Calls DoWork(int) on Derived.

Knowing When to Use Override and New Keywords (C# Programming Guide)
C# enables methods in derived classes to have the same name as methods in base classes—as long as you are very specific about how the new method should be treated. The following example demonstrates the use of the
new and override keywords.
First we declare three classes: a
base class called Car, and two classes that derive from it, ConvertibleCar and Minivan. The base class contains a single method, DescribeCar, which sends a description of the car to the console. The derived class methods also include a method called DescribeCar, which displays their unique properties. These methods also call the base class DescribeCar method to demonstrate how they have inherited the properties of the Car class.
In order to highlight the difference, the ConvertibleCar class is defined with the new keyword, while the Minivan class is defined with override.
C#
// 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.");
}
}
We can now write some code that declares instances of these classes, and calls their methods so that the objects can describe themselves:
C#
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("----------");
}
As you might expect, the output looks like this:
Four wheels and an engine.
----------
Four wheels and an engine.
A roof that opens up.
----------
Four wheels and an engine.
Carries seven people.
----------
However, in this next section of code, we declare an array of objects derived from the Car base class. This array can store Car, ConvertibleCar, and Minivan objects. The array is declared like this:
C#
public static void TestCars2()
{
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
}
We can then use a foreach loop to visit each Car object contained in the array, and call the DescribeCar method, like this:
C#
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. For more information, see
abstract

No comments:

Post a Comment