4

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?

Tom Connery
  • 110
  • 2
  • 8
  • Could you give a bit of example code? Such things are hard to talk about without some "real meat" to it ... – GhostCat Mar 05 '17 at 14:29
  • It's hard to be certain about your exact requirement but perhaps the information found here http://stackoverflow.com/questions/4326017/implementing-generic-interface-in-java could help you. – dsp_user Mar 05 '17 at 14:36
  • Done, added some detail as well. – Tom Connery Mar 05 '17 at 14:36
  • Also, please do follow the Java naming conventions. Your code is unnecessarily hard to read when you don't. – Lew Bloch Mar 05 '17 at 18:48

1 Answers1

1

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();       
    }

}
Calculator
  • 2,769
  • 1
  • 13
  • 18
  • Could you please show how you'd write the Goal class in this case? I sadly cannot really follow you there. Why would the addition of a second generic solve the problem? – Tom Connery Mar 05 '17 at 16:15
  • 1
    @DellConagher I added an implementation of your Goal class. – Calculator Mar 05 '17 at 16:24