Search code examples
javagenericscomposition

Realize a composition with generics and interfaces


I'm trying to realize the following:

My class X has a generic Y. This generic Y however needs to access resources of X and I'd like to handle this via interfaces in order to allow someone else to inherit from a arbitrary chosen class.

My current approach however results in a loop of generics:

public interface X<y extends Y<x extends X<y extends...>>> {

    Object getO();

}

public interface Y<x extends X<y extends Y<x extends ....>>> {

    void doSomething();

}

What I want to realize:

public class Goal<x X<y (this class)> implements Y {

    private final x minix;

    public Goal(x minix) {
        this.minix = minix;
    } 

    @Override
    public doSomething() {
        x.getO();
    }
}

How do I realize my goal without the common way of using an abstract class and the constructor implementation of the composition?


Solution

  • The generic type parameters of your interfaces depend on each other. To resolve the recursion you have to introduce a second type parameter for each interface:

    interface X<A extends Y<A, B>, B extends X<A, B>> {
    
        A getY(); //example    
        Object getO();
    
    }
    
    interface Y<A extends Y<A, B>, B extends X<A, B>> {
    
        B getX(); //example  
        void doSomething();
    
    }
    

    Goal class:

    public class Goal<B extends X<Goal<B>, B>> implements Y<Goal<B>, B> {
    
        private final B minix;
    
        public Goal(B minix) {
            this.minix = minix;
        } 
    
        @Override
        public B getX() {
            return minix;
        }
    
        @Override
        public void doSomething() {
            minix.getO();       
        }
    
    }