Roman Roman - 5 months ago 6
Java Question

Managing parameters upon inheritance in Java

Currently I have in my

program two classes, which share majority of the methods and both initialize pretty large
. Therefore, it would be beneficial to inherit one of them from another or both of them from a single parent class. However, the problem is that one of the classes always fills the
with specific set of values, and thus has only a parameterless constructor, while the other fills it based on user input, and thus must have only a constructor with a
parameter (which is getting then parsed to derive values that go into the
; an empty
makes no sense and throws an

Taken together, I came up with three possible solutions:

  1. Keep two fully independent but highly redundant classes.

  2. Make a common parent class with a parameterless constructor, which will lead to undesired behavior unless called from one specific child.

  3. Make a common parent class with only parameter constructor. The first class then packs its default parameters into
    , which is getting then parsed to derive the parameters again. This would affect performance drastically.

Is there a better solution, which does not have drawbacks of the listed ones?


It is a bit hard to explain specific details, but in general I want to simulate a biochemical reaction and I need objects for reagents (which are in fact mixtures in buffers) and buffers (which have standardized concentrations of chemicals in them). It would make no sense to have an 'empty' reagent or a standard buffer as reagent.


It sounds like option 3 might be the best of the three you identified. A variant would be to have the superclass constructor take a HashMap parameter that the subclasses are responsible for filling. (That avoids the efficiency issue you are worried about.)

For example

public class C1 {
   private Map<String, String> params;
   public C1(Map<String, String> params) { this.params = params; }

public class C2 extends C1 {
   public C2(String a, String b) {
      super (new HashMap<String, String>() {{
                 put("a", a);
                 put("b", b);

public class C3 extends C1 {
   private HashMap<String, String> myMap = new HashMap<>();

   public C3() {
      super (myMap);
      // now put values into myMap based on user input.

However, as they say, "the devil is in the details"1. We can't sensibly discuss the pro's and con's of these approaches in the context of your problem without knowing the details of your problem.

This illustrates that reuse-by-inheritance works best if the original classes were designed with inheritance in mind. At least your context allows you to consider a significant refactoring. In a lot of contexts, you are constrained by the extent of dependencies on the existing structure. (Especially dependencies in "customer" code.)

1 - For instance, the kind of issues that Elliott is talking about ...