Thursday, July 12, 2007

Polymorphism Example 2

class A
{
public virtual void Print()
{
Console.WriteLine("We are in Class A");
}
}
class B : A
{
public override void Print()
{
Console.WriteLine("We are in Class B.");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Print();
Console.ReadKey();
B b = new B();
b.Print();
Console.ReadKey();
A aa = new B();
aa.Print();
Console.ReadKey();
// Following code will give build error
//B bb = new A();
//b.Print();
//Console.ReadKey();
///////////////////////////////////////
A aaa = (A)b;
aaa.Print();
Console.ReadKey();
// Following code will give RUNTIME error
B bbb = (B)a;
bbb.Print();
Console.ReadKey();
}
}

No comments: