Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading inherited abstract method

Tags:

c#

I'm having a conceptual problem here, I have like this:

abstract class A
{  abstract setSomething(bool f1, bool f2);} 

class C : A {setSomethng(bool f1, bool f2){/*implementation*/}}

class B : A {setSomething(bool f1, bool f2, bool f3){/*implementation*/} !! ERROR

I'm trying to change the signature of the "setSomething" method in the subClass "B" but it gives me an error that the subClass B doesn't implement the base abstract class, is there anyway to do this? I mean to overload an inherited abstract method?

like image 515
Lisa Avatar asked Jun 26 '10 22:06

Lisa


2 Answers

When you inherit from an abstract class you either need to provide implementations for all abstract methods, or else you must declare the subclass also as abstract. You are allowed to add new methods, but you can't remove or change existing methods.

With this in mind you can provide two overloads of the method, one with and one without the extra boolean:

class B : A
{
   void setSomething(bool f1, bool f2){ /* implementation */ }
   void setSomething(bool f1, bool f2, bool f3){ /* implementation */ }
}

You might even want to consider implementing one in terms of the other:

void setSomething(bool f1, bool f2) { setSomething(f1, f2, false); }
void setSomething(bool f1, bool f2, bool f3) { /* implementation */ }

If you don't want the two parameter version to be there then you should probably reconsider if it is appropriate to use class A as the base class.

like image 167
Mark Byers Avatar answered Sep 20 '22 03:09

Mark Byers


A method is identified by name and signature. Therefore, in order to satisfy the abstract method implementation, you need to implement this method with this signature (setSomething(bool f1, bool f2)).

Whether you add an overload is not important, since the overload will be a new method and not override the other method. Of course the overridden abstract method can call the overload method in order to avoid duplicating the implementation, like so:

class B : A {
  override setSomething(bool f1, bool f2) {
    setSomething(f1, f2, false); // use the default value you want to use for f3
  }

  setSomething(bool f1, bool f2, bool f3) {
    /*implementation*/
  }
}
like image 43
Lucero Avatar answered Sep 21 '22 03:09

Lucero