Friday, November 19, 2010

OOPS!!

Inheritance and Polymorphism .

1. Inheritance


Class Animal
{
int legs;
int color;
int sound;
}

class Lion:Animal
{
int teeth;
}

class Snake:Animal
{
int length;
}



2. Polymorphism

Early Binding and Late Binding

class Animal
{
public void Feed()
{
System.Console.WriteLine ("An animal is fed here.");
}
}
class Lion: Animal
{
new public void Feed()
{
System.Console.WriteLine ("A Lion is fed here.");
}
}
class Snake: Animal
{
new public void Feed()
{
System.Console.WriteLine ("A Snake is fed here.");
}
}
class Test
{
public static void Main()
{
Animal a = new Animal();
a.Feed(); // "An animal is fed here."
Lion Leo = new Lion();
Leo.Feed(); // "A Lion is fed here."
Snake Viktor = new Snake();
Viktor.Feed(); // "A Snake is fed here."
}
}
class Test
{
public static void Main()
{
Animal[] animals = new Animal[2]; // declare an Animal array
animals[0] = new Lion(); // Add specific animals
animals[1] = new Snake();
for (int i = 0; i < 2; i++) animals[i].Feed(); // Feed the animals } }


Running this application produces the following output:
An animal is fed here.
A Lion is fed here.
A Snake is fed here

An animal is fed here.
An animal is fed here.

What has actually happened here is that the Feed() method is bound to the animals
at compile time. This is called early binding. There is no chance to examine the actual
type of animal before feeding it. We would like the compiler to not bind the method
and allow the runtime to bind it instead. That is called late binding and is used to create
polymorphic methods.

In order to overcome the problem outlined in the previous section, we use two keywords,
virtual and override. The virtual keyword is used on the base-class method and
indicates that the method can be overridden. The override keyword is used on the derived-
class method. It means that we intend to change the behavior of the method that is
inherited.

class Animal
{
virtual public void Feed()
{
System.Console.WriteLine ("An animal is fed here.");
}
}
class Lion: Animal
{
override public void Feed()
{
System.Console.WriteLine ("A Lion is fed here.");
}
}
class Snake: Animal
{
override public void Feed()
{
System.Console.WriteLine ("A Snake is fed here."); }
}
class Test
{
public static void Main()
{
Animal a = new Animal();
a.Feed(); // "An animal is fed here."
Lion Leo = new Lion();
Leo.Feed(); // "A Lion is fed here."
Snake Viktor = new Snake();
Viktor.Feed(); // "A Snake is fed here."
}
}
Now we get the behavior we want:
A Lion is fed here.
A Snake is fed here.

No comments:

Post a Comment