If at all a parent classes method is re-implemented under a child class exactly with the same signature we call it as Method Overriding.
How to override a parent classes method under child class ?
How to override a parent classes method under child class ?
- If we want to override any parent classes method under child class first under the parent the method must be defined using virtual modifier. Declaring a method as virtual under a class is giving a permission for its child classes to override.
- The methods that are declared as virtual can be overwritten as child classes using a override modifier.
class1
public virtual void Show() // overridable
class 2:class1
public override void Show() // overriding
Add a class LoadParent.cs and write the following code
using System; namespace CSharpConsole { class LoadParent { public void Test() { Console.WriteLine("Parent's test method"); } public virtual void Show() // overridable { Console.WriteLine("Parent's show method"); } public void Display() { Console.WriteLine("Parent's display method"); } } } // Add a class loadchild.cs and write the following code using System; namespace CSharpConsole { class loadchild: LoadParent { // overloading parent's test method public void Test(int x) { Console.WriteLine("Child's test method "); } public override void Show() { Console.WriteLine("Child's show method "); } public new void Display() { Console.WriteLine("Child's display method"); } static void Main() { loadchild c = new loadchild(); c.Test(); c.Test(10); c.Show(); c.Display(); Console.ReadLine(); } } }
No comments:
Post a Comment