在继承的抽象类中重写抽象方法 [英] overriding abstract methods in an inherited abstract class
问题描述
好吧,基本上我有以下问题:我试图让一个抽象类继承另一个具有抽象方法的抽象类,但是我不想在其中任何一个中实现抽象方法,因为第三个类
Okay so basically I have the following problem: I'm trying to have an abstract class inherit another abstract class that has an abstract method, but I don't want to implement the abstract method in either of them because a third class inherits from both of them:
public abstract class Command
{
public abstract object execute();
}
public abstract class Binary : Command
{
public abstract object execute(); //the issue is here
}
public class Multiply : Binary
{
public override object execute()
{
//do stuff
}
}
我正在尝试将二进制命令与一元命令,但不想/不能在其中任何一个中执行execute方法。我考虑过让Binary覆盖抽象方法(因为必须这样做),然后抛出未实现的异常。如果我将其重写,则必须声明一个主体,但是如果我将其抽象,则将隐藏继承的方法。
I'm trying to separate binary commands from unary commands but don't want to/can't implement the execute method in either. I thought about having Binary override the abstract method (since it has to), and then just throw a not implemented exception thing. If I make it override, then I must declare a body, but if I make it abstract, then I'm "hiding" the inherited method.
有什么想法吗?
推荐答案
您无需在二进制文件中声明 execute()
类,因为它已经从Command继承了。抽象方法不需要由其他抽象类实现-需求会传递到最终的具体类。
You don't need to declare execute()
in the Binary class since it's already inherited from Command. Abstract methods don't need to be implemented by other abstract classes - the requirement is passed on to the eventual concrete classes.
public abstract class Command
{
public abstract object execute();
}
public abstract class Binary : Command
{
//the execute object is inherited from the command class.
}
public class Multiply : Binary
{
public override object execute()
{
//do stuff
}
}
这篇关于在继承的抽象类中重写抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!