开发者

Overloading inherited abstract method

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

开发者_Go百科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?


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.


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*/
  }
}


You can overload the inherited abstract method, but you still must implement the abstract method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜