1

I followed this example to create a build pattern with inheritance, but in the child classes I have common fields that I would like to have in a separate class.

             BaseConfiguration
               String attr1
                    |
                   / \
                  /   \
                 /     \
                /       \
               /         \
     AConfiguration    BConfiguration
       String x          String y
           |                  |
           |                  |
           |                  |
PersonalConfiguration   ExternalConfiguration
  int a (common)           int a (common)
  int b (common)           int b (common)
  String myCustom          String other
  getAttr1() <-inherited-> getAttr1()
  getX()     <-inherited-> getY()

And I would have (without interfaces):

             BaseConfiguration
               String attr1
                    |
                   / \
                  /   \
                 /     \
                /       \
               /         \
     AConfiguration    BConfiguration
       String x          String y
           \                  /
            \                /
             \              /
           CommonConfiguration
                  int a
                  int b
                    |
                   / \
                  /   \
                 /     \
                /       \
               /         \
 PersonalConfiguration   ExternalConfiguration
   String myCustom          String other
   getA()     <-inherited-> getA()
   getB()     <-inherited-> getB()
   getAttr1() <-inherited-> getAttr1()
   getX()     <-inherited-> getY()

The idea is use an interface:

public interface MyInterface<T, U extends BaseConfiguration> {
    T build(final U baseConfiguration);
}

I am not sure if this is possible, or if it is possible by generalizing the CommonConfiguration class (CommonConfiguration<T>). I have not been able to

Alberto
  • 745
  • 1
  • 6
  • 25
  • The question is still a bit vague. Could you provide a gist of what you've accomplished so far (some code) and how you'd want it to look like (ideally)? – dshelya Jan 04 '22 at 20:29

1 Answers1

0

Java does not support multiple inheritance. It's not a bug, it's a feature, purposely decided by the language creator to avoid some hassles like dealing with the deadly diamond of death that you are looking for.

The closest thing to multiple inheritance is to implement multiple interfaces. But there's no diamond of death possible, because the interface do not lead to sub-objects: it's the same class that must implement all the interfaces.

The best way you could achieve this kind of design is to use composition over inheritance and using call forwarding to emulate inherited methods.

Christophe
  • 68,716
  • 7
  • 72
  • 138