usama8800
usama8800

Reputation: 875

Returning from submethod from super

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?

Upvotes: 0

Views: 235

Answers (4)

maczikasz
maczikasz

Reputation: 1133

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");
  }
}

Upvotes: 2

Axel
Axel

Reputation: 14169

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");
  }
}

Upvotes: 2

Messa
Messa

Reputation: 25191

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");
  }
}

Upvotes: 2

NiziL
NiziL

Reputation: 5140

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");
  }
}

Upvotes: 3

Related Questions