I have something like this:

class SuperClass {
  public void onClick(){
    if(disabled) return;
  }
}

class SubClass extends SuperClass {
  public void onClick(){
    super.onClick();
    System.out.println("Clicked");
  }
}

This outputs "Clicked" every time I click the button.

I want the SubClass onClick() to not work if disabled is true and don't want to add an extra line in every SubClass. How can I do that?

有帮助吗?

解决方案 2

Delegate to another method:

class SuperClass {
  public void onClick(){
    if(!disabled) handleOnClick();
  }
  public void handleOnClick(){
  }
}

class SubClass extends SuperClass {
  public void handleOnClick(){
    System.out.println("Clicked");
  }
}

其他提示

You should use the template method pattern

abstract class SuperClass {
  public void onClick(){
    if(!disabled) clickAction() ;
  }

  public abstract void clickAction();
}

class SubClass extends SuperClass {
  public void clickAction(){
    System.out.println("Clicked");
  }
}

Maybe something like this:

class SuperClass {
  public void onClick(){
    if(disabled) return;
    processClick();
  }
  protected void processClick() {
  }
}

class SubClass extends SuperClass {
  protected void processClick(){
    super.processClick();
    System.out.println("Clicked");
  }
}

you can't not this way anyway. The function call in the super object doesn't have any right to do anything to stop the method in the subclass from executing. What you're looking for is a TemplateMethodPattern pattern maybe. You could have something like this

 abstract class SuperClass {
  public void onClick(){
    if(disabled) return;
    doClick();
  }

  protected abstract void doClick();

}

class SubClass extends SuperClass {
  protected void doClick(){  
    System.out.println("Clicked");
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top