Deme
Deme

Reputation: 219

Inheritance in Java (design pattern)

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.

Upvotes: 0

Views: 80

Answers (2)

Jude Niroshan
Jude Niroshan

Reputation: 4460

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
  }
}

Upvotes: 2

Henry
Henry

Reputation: 146

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

Upvotes: 0

Related Questions