简体   繁体   English

重载继承的抽象方法

[英]Overloading inherited abstract method

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? 我正在尝试更改子类“B”中“setSomething”方法的签名,但是它给出了一个错误,即子类B没有实现基本抽象类,无论如何要做到这一点? 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类作为基类。

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) ). 因此,为了满足抽象方法的实现,您需要使用此签名( 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*/
  }
}

您可以重载继承的抽象方法,但仍然必须实现抽象方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM