Method Overriding - VishalBhanderi31/C-Sharp-OOPS GitHub Wiki

  • Modifying an implementation of an inherited method. In inheritance, When we want to modify an implementation the method that we inherited from the base class. Maybe this implementation which define in base class does not apply to derived class.

    public class Guitar : MusicalInstrument { //public int Id { get; set; } public override void Play() { Console.WriteLine("Play Guitar"); } }

For example,

public class Shape
{
//It has some property like Height, Width, etc.
public void Draw()
{
}
}

public class Circle : Shape
{

}

public class Image : Shape
{

}

Why is there need of Method Overriding,

public class BaseParentSuper
{
#### public void Display()
#### { Console.WriteLine("Execute BaseParentSuper");}
}

public class DerivedChildSub
{
#### public void Display()
#### { Console.WriteLine("Execute DerivedChildSub");}
}

public class Demo
{
####public static void Main()
####{
#### BaseParentSuper base = new BaseParentSuper();
#### base.Display()
#### base = new DerivedChildSub();
#### base.Display()
####}
}

hat's because the function is invoked based on the type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display() of class BC will be invoked, no matter whom b refers to. Take one more example.

Just refer Inheritance

// C# program to demonstrate the method overriding // without using 'virtual' and 'override' modifiers using System;

// base class name 'baseClass' class baseClass

{ public void show() { Console.WriteLine("Base class"); } }

// derived class name 'derived' // 'baseClass' inherit here class derived : baseClass {

// overriding 
new public void show() 
{ 
	Console.WriteLine("Derived class"); 
} 

}

class GFG {

// Main Method 
public static void Main() 
{ 
	
	// 'obj' is the object of 
	// class 'baseClass' 
	baseClass obj = new baseClass(); 
	
	
	// invokes the method 'show()' 
	// of class 'baseClass' 
	obj.show(); 
	
	obj = new derived(); 
	
	// it also invokes the method 
	// 'show()' of class 'baseClass' 
	obj.show(); 
	
} 

}