Thursday, May 17, 2018

C# : Method overriding

Creating the method in a derived class with same name, same parameters and same return type as in base class is called as method overriding.
Method overriding is the example of run time polymorphism,how its is the part of run time polymorphism i will explain in detail.
 
Some Key Points of  Method overriding
  •  Method overriding is only possible in derived class not within the same class where the method is declared.
  • Only those methods are overrides in the derived class which is declared in the base class with the help of virtual keyword or abstract keyword.
 e.g
  1. public class Account
  2.   {  
  3.     public virtual int balance()  
  4.     {  
  5.         return 10;  
  6.     }  
  7.   }  
  8. public class Amount:Account
  9. {  
  10.      
  11.     public override int balance()  
  12.     {  
  13.         return 500;  
  14.     }  
  15. }  
 Output of the above Program is
  • 10 and 500
In the above small program their are two classes Account and Amount and both the classes contain same method Name that balance() in which Account class method  returns 10 and  Amount class returns 500 at run time because Account class  method is overridden in a class Amount.
The Method overriding is very useful when  we wants to return different output of same method in different class according to the need.
Let us consider the example I wants to provide the discount on particular product according to the Customer category that A,B,C in this scenario suppose A,B,C are the classes and Discount is the class which contains virtual CustDiscount () method ,then i simply override it on class A,B,C instead of writing three different methods for each class.

No comments:

Post a Comment