overriding abstract methods in an inherited abstract class

左心房为你撑大大i 提交于 2019-12-14 00:20:59

问题


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

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.

Any thoughts?


回答1:


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



回答2:


Just omit the declaration of execute() in Binary at all. Since Binary is abstract as well, you don't have to implement any abstract methods of its ancestors.



来源:https://stackoverflow.com/questions/13518381/overriding-abstract-methods-in-an-inherited-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!