Java: Implement a default parent class (super class) that will set members for all subclasses

Java: Implement a default parent class (super class) that will set members for all subclasses … here is a solution to the problem.

Java: Implement a default parent class (super class) that will set members for all subclasses

Example:

I want

most components to have a specific background color and a specific foreground color, and if the default color seems off, I want to change it. The main ways to do this are setBackgroundColor() and setForegroundColor().

The most reasonable 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 right thing to do? Does such a construct also have a special name, for example in Factory?

Solution

Yes, your design shows that you need abstraction. You can encapsulate the common behavior of some methods in abstract classes, which are implemented by 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.
}

Because this is an abstract class, it cannot be instantiated. You will need at least one specific extension and create an instance of that extension.

Related Problems and Solutions