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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Akkiraju IvaturiPosted Sep 18, 2012, 11:24 AM
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.
VulpesPosted Sep 18, 2012, 11:22 AM
Shivanand ArurPosted Sep 18, 2012, 11:17 AM
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.