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
- public class Account
- {
- public virtual int balance()
- {
- return 10;
- }
- }
- public class Amount:Account
- {
- public override int balance()
- {
- return 500;
- }
- }
- 10 and 500
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