How to override any method
Anyone can tell me how to override any method
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Shivanand ArurRank #920 · 2.3K reputationPosted Sep 18, 2012, 7:17 AM EDT
class A
{
public virtual int Method1()
{
int x = 10;
return x;
}
}
class B : A
{
public override int Method1()
{
int y = 20;
return y;
}
}
Class B inherits A and the method in the Class A has to be defined with the Virtual keyword.... The Overridden method should have the same method name, return type and the same number of arguments.... Hope this helps you.
Please mark this as Answer if it helps you. Thanks.
VulpesRank #55 · 29.2K reputationPosted Sep 18, 2012, 7:22 AM EDT
Akkiraju IvaturiRank #473 · 5.3K reputationPosted Sep 18, 2012, 7:24 AM EDT
Base class:
=============
public Class A
{
public virtual int sum(int a, int b)
{
return (a+b);
}
}
Child Class inheriting base class:
======================
public class B:A
{
public override int sum(int a, int b)
{
return (a+b)+50;
}
}
To override a method, first the base class should have a method decorated with virtual keyword. Virtual keyword tells the compiler that the child class is going to override the implementation. Override must be decorated for the method in the child class to inform compiler that we are defining our own implementation in the child class. By default the child class inherit all the properties and methods of the base class and based on the access modifiers can use base class methods.
If you want to call a base class method in child class method you have to refer the base class method by base.sum(4,5). Note the signature and access modifier should be same in both the child class and parent class for overriding.
Let me know if you have any questions.