'How can I combine multiple sets of properties in Java to avoid duplication?

The title might be a little confusing, but let me explain what I mean. I'm trying to create classes that all have the same base fields, but then each of the classes has fields that are shared by some, but not all like this:

abstract class BaseClass {
    private final int a;
    private final int b;
    private final int c;
}

class A extends BaseClass {
    private final int j;
    private final int y;
}

class B extends BaseClass {
    private final int j;
    private final int x;
}

class C extends BaseClass {
    private final int k;
    private final int y;
}

class D extends BaseClass {
    private final int k;
    private final int x;
}

I also drew up a little diagram to illustrate what I'm trying to accomplish

Now I know that what I'm describing here is multiple inheritance, but unfortunately (or fortunately I suppose, depending on your perspective) Java doesn't support multiple inheritance. That leaves me with 2 options:

  1. Just duplicate the fields wherever I need them like in the example above

  2. Put the properties into separate classes which then become the fields in the concrete classes like this:

abstract class BaseClass {
    private final int a;
    private final int b;
    private final int c;
}

class PropertiesClassJ {
    private final int j;
}

class PropertiesClassK {
    private final int k;
}

class PropertiesClassX {
    private final int x;
}

class PropertiesClassY {
    private final int y;
}

class ConcreteClass1 extends BaseClass {
    private final PropertiesClassJ propertiesClassJ;
    private final PropertiesClassK propertiesClassK;
}

class ConcreteClass2 extends BaseClass {
    private final PropertiesClassJ propertiesClassJ;
    private final PropertiesClassX propertiesClassX;
}

Obviously option 1 is not really the way to go, but I don't really like option 2 either since it doesn't really match the structure that the final object is trying to represent. Is there another option here to get what I want, or is option 2 my best choice?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source