0

I'm refactoring some code, abstracting functionality from a subclass to a helper class, but I found that I need methods from the superclass in the helper class.

I was wondering if there is a design pattern that can help me to do this. Or any other suggestions.

public class Notification(){
    public void printMessage(String k, String str){
        //Some code
    }
}

public class NotificationImpl1 extends Notification(){
    ErrorHelper helper = new ErrorHelper();
    helper.showMessage("test");
}

public class ErrorHelper(){
    public void showMessage(String msg){
        // need to call printMessage() here
    }
}

Thanks in advance.

1
  • a possible solution is to declare the subclass Error helper outside of NotificationImpl1 and just add extends Notification to class ErrorHelper this would give you access to all the functionality of the parent, or if it is just a small amount of code just copy and paste the method you need. Commented Nov 25, 2016 at 3:35

2 Answers 2

2
public class ErrorHelper(){

  Notification notification = null;

  public ErrorHelper(Notification notification){
    this.notification = notification;
  }

  public void showMessage(String k_str, String msg){
    this.notification.printMessage(k_str, msg);
    // need to call printMessage() here
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I also agree with this solution.
0
public class Notification(){
   public void printMessage(String k, String str){
      //Some code
   }
}

public class NotificationImpl1 extends Notification(){
     public void method1() {
          ErrorHelper helper = new ErrorHelper();
          helper.showMessage("test", this);
     }
}

public class ErrorHelper() {
    public void showMessage(String msg, Notification notification){
       // Change msg to necessary 2 parameters.
       String k = getK(msg);
       String str = getStr(msg);
       notification.printMessage(k, str);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.