Reputation: 875
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
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
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
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
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