There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Tuesday, April 18, 2006


Polymorphism implies that different objects behave in different forms, by exposing different functionalities that is the properties and methods; by the use of the same public interface.

The behavior differs since various classes can implement many different un-related interfaces and the same interface can be implemented by various classes.

- Interface Polymorphism -

One class can implement from one or more interfaces; resulting a class that instantiated objects will behave in a specific way.
Let’s see what an interface is. An interface defines the agreed structure of a class behavior. Behavior of an object will be determined by the properties and the methods which they expose. There for an interface has the method definitions, where the class can implement and override them.

interface IVehicle
void drive();
// this is the method definition

// -------------------------------------------

public class Car : IVehicle
virtual void drive()
// this is the method implementation

According to the above example; if we create a Lorry class which will implement from the IVehicle, and write a method implementation for the drive() method; then the objects created from the car class will differ from the objects created from the lorry class. As you see now its clear that even the both classes implements from a single interface the end result would differ.

Note: Further the methods defined with in the interface are by default public and abstract.
When you are overriding a method is an interface you need to use the key word “virtual”, in order to override. Further, you are allowed to define properties in interfaces but not fields, this ensures that (classes that interact with the interfaces) it does not have access to the internal data of objects.

- Inheritance polymorphism –

One class can inherit from another, where the base class will contain the complete functionality. That is, the base class will contain the method implementations; and the inherited classes will contain the base class functionality plus the additional functionalities as well.
Let’s see how we can do this in code.

public abstract class vehicle
public abstract void drive();

public class car : vehicle
public override void drive()
//this is the new implementation

In this scenario as well, another class which will inherit the vehicle class will have the same drive() method plus some additional functionality.

In the case of maintainability, as you may see, when we code for abstract classes; and once we need some additional functionality, we need to change the existing base class. But if we have code for interfaces; then it’s a matter of adding new functionality, with out touching the existing code. There fore coding for interfaces are easy; in the case of maintenance when adding new functionality.


Post a Comment

<< Home