Implement composition with generics and interfaces

I am trying to understand the following:

My class X has a common Y. However, this generic Y needs to access the resources of X, and I would like to handle this through interfaces to allow someone else to inherit from an arbitrary selected class.

My current approach, however, leads to a generic cycle:

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 understand:

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 to realize your goal without a common way to use an abstract class and implement a composition constructor?

+4
source share
1 answer

The general parameters of your interface depend on each other. To enable recursion, you must enter a second parameter type 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();

}

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

}
+1

Source: https://habr.com/ru/post/1671519/


All Articles