In Object Oriented Programming, Polymorphism allows programmers to have same interface for different type of Objects. Depending upon the type of object, interface produces different results.
This is called late-binding. In C#, it is achieved by combination of virtual functions, derived classes, and with 'new' & 'override' keywords.
using System;
public class Parent
{
public virtual void Print()
{
Console.WriteLine ("This is parent class");
}
public virtual void Print2()
{
Console.WriteLine ("Print2: This is parent class");
}
}
public class Child : Parent
{
public override void Print()
{
Console.WriteLine ("This is child class");
}
public new void Print()
{
Console.WriteLine ("Print2: This is child class");
}
}
public class MyClass
{
public static void Main()
{
Parent p;
p = new Parent();
p.Print(); p.Print2();
p = new Child();
p.Print(); p.Print2();
}
}
Following is the output:
This is parent classPrint2: This is parent class
This is child class
Print2: This is parent class
If we use 'new' keyword instead of 'override' keyword, it doesn't override base class function but hide it from base class object.
No comments:
Post a Comment