Java 默认实现还是抽象方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3595731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:22:35  来源:igfitidea点击:

Default implementation or abstract method?

javapolymorphismdefaultabstract-methods

提问by Scott

Is it better to put a default implementation of a method in a superclass, and override it when subclasses want to deviate from this, or should you just leave the superclass method abstract, and have the normal implementation repeated across many subclasses?

是将方法的默认实现放在超类中,并在子类想要偏离它时覆盖它,还是应该让超类方法抽象,并在许多子类中重复正常实现?

For example, a project I am involved in has a class that is used to specify the conditions in which it should halt. The abstract class is as follows:

例如,我参与的一个项目有一个类,用于指定它应该停止的条件。抽象类如下:

public abstract class HaltingCondition{
    public abstract boolean isFinished(State s);
}

A trivial implementation might be:

一个简单的实现可能是:

public class AlwaysHaltingCondition extends HaltingCondition{
    public boolean isFinished(State s){
        return true;
    }
}

The reason we do this with objects is that we can then arbitrarily compose these objects together. For instance:

我们对对象这样做的原因是我们可以任意将这些对象组合在一起。例如:

public class ConjunctionHaltingCondition extends HaltingCondition{
    private Set<HaltingCondition> conditions;

    public void isFinished(State s){
        boolean finished = true;
        Iterator<HaltingCondition> it = conditions.iterator();
        while(it.hasNext()){
            finished = finished && it.next().isFinished(s);
        }
        return finished;
    }
}

However, we have some halting conditions that need to be notified that events have occurred. For instance:

但是,我们有一些停止条件需要通知事件已经发生。例如:

public class HaltAfterAnyEventHaltingCondition extends HaltingCondition{
    private boolean eventHasOccurred = false;

    public void eventHasOccurred(Event e){
        eventHasOccurred = true;
    }

    public boolean isFinished(State s){
        return eventHasOccurred;
    }
}

How should we best represent eventHasOccurred(Event e)in the abstract superclass? Most subclasses can have a no-op implementation of this method (e.g. AlwaysHaltingCondition), while some require a significant implementation to operate correctly (e.g. HaltAfterAnyEventHaltingCondition) and others do not need to do anything with the message, but must pass it on to their subordinates so that they will operate correctly (e.g. ConjunctionHaltingCondition).

我们应该如何eventHasOccurred(Event e)在抽象超类中最好地表示?大部分子类可以有一个无操作实现此方法(例如AlwaysHaltingCondition),而一些需要显著实现正常运行(例如HaltAfterAnyEventHaltingCondition)和其他不需要与消息做任何事情,但必须把它传递给自己的下属,这样它们将正确运行(例如ConjunctionHaltingCondition)。

We could have a default implementation, which would reduce code duplication, but would cause some subclasses to compile yet not operate correctly if it wasn't overridden, or we could have the method declared as abstract, which would require the author of every subclass to think about the implementation they were providing, although nine times out of ten it would be a no-op implementation. What are the other pros and cons of these strategies? Is one much better than the other?

我们可以有一个默认实现,这将减少代码重复,但如果没有被覆盖,会导致一些子类编译但无法正确运行,或者我们可以将方法声明为抽象,这将要求每个子类的作者想想他们提供的实现,尽管十有八九是无操作实现。这些策略的其他优缺点是什么?一个比另一个好很多吗?

采纳答案by Jon Skeet

One option is to have another abstract subclass, to use as the superclass for all implementations which dowant to use the default implementation.

一种选择是有另一个抽象类,作为超类的所有实现使用要使用的默认实现。

Personally I usuallyleave non-final methods abstract in an abstract class (or just use interfaces instead) but it definitely depends on the situation. If you have an interface with many methods, and you want to be able to just opt in to someof them, for example, then an abstract class which implements the interface in a no-op way for every method is fine.

就我个人而言,我通常将非最终方法抽象在抽象类中(或者只是使用接口),但这绝对取决于具体情况。例如,如果您有一个包含许多方法的接口,并且您希望能够选择加入其中的一些方法,那么一个抽象类以无操作方式为每个方法实现该接口就可以了。

You need to evaluate each case on its merits, basically.

基本上,您需要评估每个案例的优点。

回答by Woot4Moo

If you are leaving the super class method abstract you may want to look into utilizing an Interface (not to be confused with an interface). As the Interface is one that does not provide a concrete implementation.

如果您将超类方法抽象化,您可能需要考虑使用接口(不要与接口混淆)。因为接口是一个不提供具体实现的接口。

Scott

斯科特

To expand, when we as programmers are instructed to code to an interface often times new, and sometimes experienced, developers will assume incorrectly that it is in reference to the keyword Interface wherein no implementation details may be found. However, the more clear way of saying this is that any top level object can be treated as an interface which can be interacted with. For instance an abstract class called Animal would be an interface would a class called Cat that would inherit from Animal.

展开来说,当我们作为程序员被指示对一个接口进行编码时,通常是新的,有时是经验丰富的,开发人员会错误地认为它是参考关键字 Interface,其中可能找不到实现细节。然而,更明确的说法是,任何顶级对象都可以被视为可以与之交互的接口。例如,一个名为 Animal 的抽象类将是一个接口,一个名为 Cat 的类将继承自 Animal。

回答by Michael

It sounds like you are concerned about setting that boolean variable when the event happens. If the user overrides eventHasOccurred(), then the boolean variable will not be set and isFinished()will not return the correct value. To do this, you can have one abstract method which the user overrides to handle the event and another method which calls the abstract method and sets the boolean value (see the code sample below).

听起来您担心在事件发生时设置该布尔变量。如果用户覆盖eventHasOccurred(),则布尔变量将不会被设置,isFinished()也不会返回正确的值。为此,您可以拥有一个用户重写以处理事件的抽象方法,以及另一个调用抽象方法并设置布尔值的方法(请参阅下面的代码示例)。

Also, instead of putting the eventHasOccurred()method in the HaltingConditionclass, you can just have the classes that need to handle events extend a class which defines this method (like the class below). Any class that does not need to handle events can just extend HaltingCondition:

此外,您可以将需要处理事件的类扩展为定义此方法的类(如下面的类),而不是将eventHasOccurred()方法放入HaltingCondition类中。任何不需要处理事件的类都可以扩展HaltingCondition

public abstract class EventHaltingCondition extends HaltingCondition{
  private boolean eventHasOccurred = false;

  //child class implements this
  //notice how it has protected access to ensure that the public eventHasOccurred() method is called
  protected abstract void handleEvent(Event e);

  //program calls this when the event happens
  public final void eventHasOccurred(Event e){
    eventHasOccurred = true; //boolean is set so that isFinished() returns the proper value
    handleEvent(e); //child class' custom code is executed
  }

  @Override
  public boolean isFinished(){
    return eventHasOcccurred;
  }
}

EDIT (see comments):

编辑(见评论):

final EventHaltingCondition condition = new EventHaltingCondition(){
  @Override
  protected void handleEvent(Event e){
    //...
  }
};
JButton button = new JButton("click me");
button.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent actionEvent){
    //runs when the button is clicked

    Event event = //...
    condition.eventHasOccurred(event);
  }
});

回答by Steve

If you are going to put any implementation in the abstract base class, it should be the code for the sub-classes that use the no-op implementation, since this is an implementation that makes sense for the base class as well. If there were no sensible implementation for the base class (e.g., if there was no sensible no-op for the method you're discussing here), then I'd suggest leaving it abstract.

如果您打算将任何实现放在抽象基类中,那么它应该是使用 no-op 实现的子类的代码,因为这也是对基类有意义的实现。如果基类没有合理的实现(例如,如果您在此处讨论的方法没有合理的空操作),那么我建议将其保留为抽象的。

With respect to duplicated code, if there are "families" of classes that all use the same implementation of the method and you don't want to duplicate the code across all classes in the family, you might simply use helper classes per family that supply these implementations. In your example, a helper for classes that pass down the events, a helper for classes accept and record the event, etc.

关于重复代码,如果存在所有使用相同方法实现的类的“系列”,并且您不想在系列中的所有类中复制代码,您可以简单地使用每个系列提供的辅助类这些实现。在您的示例中,传递事件的类的助手,类的助手接受并记录事件等。

回答by Juri

I encountered a similar scenario when I created the basic outline (class hierarchy) of an application I was developing together with others at work. My choice for placing a method abstract(and consequently to force its implementation) was for communicationpurposes.

我在创建与其他人一起开发的应用程序的基本大纲(类层次结构)时遇到了类似的情况。我选择放置一个方法抽象(并因此强制其实现)是为了交流目的。

Basically the other team mates had somehow to explicitly implement the method and therefore first of all notice its presence and second agreeon what they return there, even if it is just the default implementation.

基本上其他队友必须以某种方式明确实现该方法,因此首先注意它的存在,然后就他们返回的内容达成一致,即使它只是默认实现。

Default implementations in base classes often get overlooked.

基类中的默认实现经常被忽视。