Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a Base Class method and add a parameter

I have this in my base class:

protected abstract XmlDocument CreateRequestXML();

I try to override this in my derived class:

protected override XmlDocument CreateRequestXML(int somevalue)
{
    ...rest of code
}

I know this is an easy question but because I've introduced a param is that the issue? The thing is, some of the derived classes may or may not have params in its implementation.

like image 786
user72603 Avatar asked Mar 11 '09 04:03

user72603


People also ask

How do you override a base class method?

override (C# reference) An override method provides a new implementation of the method inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. An override method must have the same signature as the overridden base method.

Can we pass parameters in override method?

As per the rule, while overriding a method in subclass, parameters cannot be changed and have to be the same as in the super class.

Would you override a method of a base class?

Method overriding is a feature that allows a subclass, or a child class, to specifically implement a method already given in one of its super-classes, or parent classes, in any object-oriented programming language. Thus, the process of redefining a parent class's method in a subclass is known as method overriding.

How can we override a base class method in an extended class?

Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter . The Employee class provides a howPaid method that will override the corresponding method in the base class.


2 Answers

When you override a method, with the exception of the word override in place of virtual or abstract, it must have the exact same signature as the original method.

What you've done here is create a new unrelated method. It is not possible to introduce a parameter and still override.

like image 89
JaredPar Avatar answered Nov 14 '22 23:11

JaredPar


If some of the derived classes need paramters and some do not, you need to have two overloaded versions of the method. Then each derived class can override the one it needs.

class Foo {    
    protected abstract XmlDocument CreateRequestXML(int somevalue);
    protected abstract XmlDocument CreateRequestXML();
};

class Bar : public Foo {    
    protected override XmlDocument CreateRequestXML(int somevalue) { ... };
    protected override XmlDocument CreateRequestXML()
        { CreateRequestXML(defaultInt); }
};

This of course introduces a problem of the user calling the wrong one. If there is no acceptable default for the extra paramter, you may have to throw an exception in the derived class if the wrong version is called.

like image 33
Steve Rowe Avatar answered Nov 14 '22 22:11

Steve Rowe