I understand overriding a method/function redefines its implementation in the derived class from its implementation in the base class.
Now what confuses me, is if I override a class in ASP.NET such as CreateChildControls()
(I picked it randomly for no particular reason), VS2008 auto generates:
protected override void CreateChildControls()
{
base.CreateChildControls();
}
Good enough, the default implementation just calls the base class' CreateChildControls()
.
So if I want to run some code, since I do not know how base.CreateChildControls()
, should I do this:
protected override void CreateChildControls()
{
/*My Code Here*/
base.CreateChildControls();
}
or, ignore what base.CreateChildControls()
altogether and just do
protected override void CreateChildControls()
{
/*My Code Here*/
}
Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.
Method overriding limitations Both the parent class and the child class must have the same method name, the same return type and the same parameter list. Methods declared final and static cannot be overridden. A method cannot be overridden if it cannot be inherited. That is, it must be an IS-A relationship.
Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
class A { virtual void X() { Console. WriteLine("x"); } } class B : A { override void X() { Console. WriteLine("y"); } } class Program { static void Main() { A b = new B(); // Call A.X somehow, not B.X... }
That's up to you. Generally, you want to call the base class method because it might do a lot of stuff you're not privy to (especially in a class you don't control .. get it? Control.) But, if you are very confident you don't need (or want) the base class "stuff" to happen, you can remove the call.
It's simply a question of whether you want to entirely replace the behavior or add behavior.
For something like CreateChildControls, you will probably retain the call to the base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With