Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

swing

awt

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?

like image 988
demonoga Avatar asked Apr 18 '26 00:04

demonoga


1 Answers

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.

like image 106
NiVeR Avatar answered Apr 19 '26 15:04

NiVeR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!