I have a Swing application in which I have multiple windows with different goals but they all have 2 things in common:
- They use a specific object which is business logic related
- They have to update some widgets with the specific object’s stuff
So, in order to avoid redundancy of code, I wanted to share some of those routines.
Maybe an example can be more clear:
public class WindowA {
private JLabel labelA;
// ...
private void updateLabelInACertainManner() {
labelA.setText(this.specificObject.getText());
}
}
public class WindowB {
private JLabel labelB;
// ...
private void updateLabelInACertainManner() {
labelA.setText(this.specificObject.getText());
}
}
How can I share updateLabelInACertainManner(), knowing that specificObject references the same object in both classes ?
I was thinking about inheriting both WindowA and WindowB from a WindowRoot which contains the method but how to do so having labelA and labelB are not the same object, not necessarily created in same way?
You could pass the label whose text should be changed as a parameter to the method in the superclass:
Or you could write a getter for the label in the specific subclasses:
And the same for
specificObject.