C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding.
In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the ways by which C# achieve Run Time Polymorphism(Dynamic Polymorphism).
The method that is overridden by an override declaration is called the overridden base method. An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override.
Example:
class base_class
{
public void gfg();
}
class derived_class : base_class
{
public void gfg();
}
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();
d.gfg();
}
}
Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.
In C# we can use 3 types of keywords for Method Overriding:
- virtual keyword: This modifier or keyword use within base class method. It is used to modify a method in base class for overridden that particular method in the derived class.
- override: This modifier or keyword use with derived class method. It is used to modify a virtual or abstract method into derived class which presents in base class.
class base_class { public virtual void gfg(); } class derived_class : base_class { public override void gfg(); } class Main_Method { static void Main() { derived d_class = new derived_class(); d.gfg(); base_class b = new derived_class(); b.gfg(); } }Here first, d refers to the object of the class derived_class and it invokes gfg() of the class derived_class then, b refers to the reference of the class base and it hold the object of class derived and it invokes gfg() of the class derived. Here gfg() method takes permission from base class to overriding the method in derived class.
Example 1: Method Overriding without using virtual and override modifiers
// C# program to demonstrate the method overriding// without using 'virtual' and 'override' modifiersusingSystem;// base class name 'baseClass'classbaseClass{publicvoidshow(){Console.WriteLine("Base class");}}// derived class name 'derived'// 'baseClass' inherit hereclassderived : baseClass{// overridingnewpublicvoidshow(){Console.WriteLine("Derived class");}}classGFG {// Main MethodpublicstaticvoidMain(){// 'obj' is the object of// class 'baseClass'baseClass obj =newbaseClass();// invokes the method 'show()'// of class 'baseClass'obj.show();obj =newderived();// it also invokes the method// 'show()' of class 'baseClass'obj.show();}}chevron_rightfilter_noneOutput:Base class Base class
Explanation: In this program the object obj invokes class baseClass two times and call the method show() of class baseClass. To avoid this problem we use virtual and override keyword.
Example 2: Method overriding using virtual and override modifiers.
// C# program to illustrate the use of//'virtual' and 'override' modifiersusingSystem;classbaseClass {// show() is 'virtual' herepublicvirtualvoidshow(){Console.WriteLine("Base class");}}// class 'baseClass' inherit// class 'derived'classderived : baseClass{//'show()' is 'override' herepublicoverridevoidshow(){Console.WriteLine("Derived class");}}classGFG {// Main MethodpublicstaticvoidMain(){baseClass obj;// 'obj' is the object// of class 'baseClass'obj =newbaseClass();// it invokes 'show()'// of class 'baseClass'obj.show();// the same object 'obj' is now// the object of class 'derived'obj =newderived();// it invokes 'show()' of class 'derived'// 'show()' of class 'derived' is overridden// for 'override' modifierobj.show();}}chevron_rightfilter_noneOutput:Base class Derived class
- base Keyword: This is used to access members of the base class from derived class. It basically used to access constructors and methods or functions of the base class. The base keyword cannot use within a static method. Base keyword specifies which constructor of the base class should be invoked while creating the instances of the derived class.
Use of Base keyword:
- Call methods or functions of base class from derived class.
- Call constructor internally of base class at the time of inheritance.
Example 1:
// C# program to show the use of 'base'// keyword in method overridingusingSystem;// base classpublicclassweb {stringname ="GeeksForGeeks";// 'showdata()' is member method,// declare as virtualpublicvirtualvoidshowdata(){Console.WriteLine("Website Name: "+ name);}}// derived class// class 'web' is inherits// class 'stream'classstream : web {strings ="Computer Science";//'showdata()' is overridden// in derived classpublicoverridevoidshowdata(){// Calling 'showdata()' of base// class using 'base' keywordbase.showdata();Console.WriteLine("About: "+ s);}}classGFG {// Main MethodstaticvoidMain(){// 'E' is object of class stream// also works as object of// class 'web'stream E =newstream();// it first invokes 'showdata()'// of class 'web' then it invokes// 'showdata()' of class 'stream'E.showdata();}}chevron_rightfilter_noneOutput:Website Name: GeeksForGeeks About: Computer Science
Example 2: How base keyword specifies the calling of base-class constructor from derived class when derived class instances are created.
// C# program to show how base keyword// specifies the calling of base-class// constructor from the derived class// when derived class instances are createdusingSystem;// base classpublicclassclssA {intn1, n2;// default constructorpublicclssA(){Console.WriteLine("Default Constructor Invoked");}// parameterized constructorpublicclssA(inti,intj){// consturct valuesn1 = i;n2 = j;Console.WriteLine("Parameterized Constructor Invoked");Console.WriteLine("Invoked Values are: "+ n1 +" and "+ n2);}}// derived classpublicclassDerivedClass : clssA{// This constructor will instantiate// 'clssA()' [no argument constructor]// using 'base' keywordpublicDerivedClass() :base() { }// This constructor will instantiate// 'clssA(int i, int j)' [parameterized// constructor] using 'base' keywordpublicDerivedClass(inti,intj) :base(i, j) { }// Main MethodstaticvoidMain(){// invoke no argumanet constructorDerivedClass d1 =newDerivedClass();Console.WriteLine();// invoke parameterized constructorDerivedClass d2 =newDerivedClass(10, 20);}}chevron_rightfilter_noneOutput:
Default Constructor Invoked Parameterized Constructor Invoked Invoked Values are: 10 and 20
Example 3: It shows how base keyword specifies the base-class constructor called from derived class and also calling of a method using the base keyword from the derived class.
// C# program to show how 'base' keyword specifies// the base-class constructor that called from// derived class and also calling a method 'swap'// from derived class using base keywordusingSystem;// base classpublicclassclssA {publicintn1, n2;// default constructorpublicclssA(){Console.WriteLine("In clssA 'no argument constructor' invoked");}// parameterized constructorpublicclssA(inti,intj){// consturct valuesn1 = i;n2 = j;Console.WriteLine("in clssA 'parameterized constructor' invoked");Console.WriteLine("the invoked values are "+ n1 +" and "+ n2);Console.WriteLine();}publicvirtualvoidswap(){Console.WriteLine("swap function of base class(clssA) invoked");Console.WriteLine("Before swap num1 = {0} and num2 = {1}", n1, n2);// swappingintt = n1;n1 = n2;n2 = t;Console.WriteLine("After swap num1 = {0} and num2 = {1}", n1, n2);}}// derived classpublicclassDerivedClass : clssA {// This constructor will instantiate// 'clssA' [no argument constructor]// using 'base' keywordpublicDerivedClass() :base() { }// This constructor will instantiate// 'clssA' [parameterized constructor]// using 'base' keywordpublicDerivedClass(inti,intj) :base(i, j) { }publicoverridevoidswap(){// it access the swap funtion of// 'clssA' using 'base' keywordbase.swap();Console.WriteLine();Console.WriteLine("Swap function of derived class invoked");Console.WriteLine("Before swap num1 = {0} and num2 = {1}", n1, n2);// swappingintt = n1;n1 = n2;n2 = t;Console.WriteLine("After swap num1 = {0} and num2 = {1}", n1, n2);}// Main MethodstaticvoidMain(){// invoke no argumanet constructorDerivedClass d1 =newDerivedClass();Console.WriteLine();// invoke parameterized constructorDerivedClass d2 =newDerivedClass(10, 20);// calling swap functiond2.swap();}}chevron_rightfilter_noneOutput:
In clssA 'no argument constructor' invoked in clssA 'parameterized constructor' invoked the invoked values are 10 and 20 swap function of base class(clssA) invoked Before swap num1 = 10 and num2 = 20 After swap num1 = 20 and num2 = 10 Swap function of derived class invoked Before swap num1 = 20 and num2 = 10 After swap num1 = 10 and num2 = 20
Note:
- Method overriding is possible only in derived classes. Because a method is overridden in the derived class from base class.
- A method must be a non-virtual or static method for override.
- Both the override method and the virtual method must have the same access level modifier.
Recommended Posts:
- Difference between Method Overriding and Method Hiding in C#
- C# | Dictionary.Add() Method
- C# | String.Contains() Method
- Extension Method in C#
- C# | IndexOfAny() Method
- C# | StartsWith() Method
- C# | Math.Sin() Method
- C# | Math.Cos() Method
- C# | Math.Log() Method
- C# | Math.Tan() Method
- C# | Trim() Method
- C# | CopyTo() Method
- C# | EndsWith() Method
- Method Hiding in C#
- C# | Math.Abs() Method | Set - 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : subhasis mohanty




