Inheritance without polymorphism
public class BaseA { public void Display() { Console.WriteLine('Display Method BaseA'); } } public class DerivedA : BaseA { //Warning InheritanceExample.DerivedA.Display()' hides inherited member 'InheritanceExample.BaseA.Display()'. //Use the new keyword if hiding was intended. public void Display() { Console.WriteLine('Display Method DerivedA'); } } public class DerivedB : BaseA { public void Display() { Console.WriteLine('Display Method DerivedB'); } }
Main Method
static void Main(string[] args) { BaseA AObj = new BaseA(); AObj.Display(); DerivedA ADerObj = new DerivedA(); ADerObj.Display(); BaseA AObj1 = new DerivedA(); AObj1.Display(); Console.ReadLine(); } <strong>Output</strong> Display Method BaseA Display Method DerivedA Display Method BaseA //Error 1 Cannot implicitly convert type BaseA' to DerivedA'. //An explicit conversion exists (are you missing a cast?) DerivedA AObj2 = new BaseA(); AObj2.Display(); //Unable to cast object of type BaseA' to type DerivedA'. DerivedA AObj2 = (DerivedA)new BaseA(); AObj2.Display();
Using new keyboard:
public class BaseA { public virtual void Display() { Console.WriteLine('Display Method BaseA'); } } public class DerivedA : BaseA { public new virtual void Display() { Console.WriteLine('Display Method DerivedA'); } } public class DerivedB : BaseA { public new virtual void Display() { Console.WriteLine('Display Method DerivedB'); } }
Inheritance using polymorphism
public class BaseA { public virtual void Display() { Console.WriteLine('Display Method BaseA'); } } public class DerivedA : BaseA { public override void Display() { Console.WriteLine('Display Method DerivedA'); } } public class DerivedB : BaseA { public override void Display() { Console.WriteLine('Display Method DerivedB'); } } static void Main(string[] args) { BaseA AObj = new BaseA(); AObj.Display(); DerivedA ADerObj = new DerivedA(); ADerObj.Display(); BaseA AObj1 = new DerivedA(); AObj1.Display(); BaseA AObj2 = new DerivedB(); AObj2.Display(); //DerivedA AObj3 = (DerivedA)new BaseA(); Casting error // AObj2.Display(); Console.ReadLine(); }
Output
Display Method BaseA
Display Method DerivedA
Display Method DerivedA
Display Method DerivedB