Java: Implementing a default super class that will set members for all subclasses

demonoga :

Example:

I want to make most of the Components have a certain background color and certain foreground color, and I want to change it if default Color seems off. Primary methods to achieve this are setBackgroundColor() and setForegroundColor().

Most plausible answer for me is:

public class DefaultComponent {
  private static final BACKGROUND_COLOR = Color.GRAY;
  private static final FOREGROUND_COLOR = Color.WHITE;
  public static void setComponent(Component comp) {
    comp.setBackground(backgroundColor);
    comp.setForeground(foregroundColor);
  }
}

Is this the correct approach? Also is there a special name for such a construct, such as in Factory?

NiVeR :

Yes, your design suggests that you need an abstraction. The common behaviour of certain methods can be enclosed in the abstract class, and the specific methods will be implemented by the concrete classes.

public abstract class GenericComponent {
  private static final BACKGROUND_COLOR = Color.GRAY;
  private static final FOREGROUND_COLOR = Color.WHITE;
  public static void setComponent(Component comp) {
    comp.setBackgroundColor(backgroundColor);
    comp.setForegroundColor(foregroundColor);
  }

  //here provide a list of abstract methods that each extension class will implement.
}

As this is an abstract class, it can't be instantiated. You will need to have at least one concrete extension, and create instances of that one.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103452&siteId=1