Struggling to combine method chaining with class extensions

63 Views Asked by At

I'm trying to combine method chaining with class extensions and a method that is defined in a base class. However, I struggle to get it to work, as I am not very familiar with Generics yet. Could someone maybe help me to get this to work? It would be really appreciated. Thanks!

Current situation:

public abstract class A<T extends A<?>> extends F // the base class, all others extend this one (either direct or indirect)
public T isLoaded() { // method defined in class A
    // Omitted
    return (T) this;
}

public class B extends A<B> // One of the classes that extends the base class
public D tapButton() // Method defined in class B

public class C extends A<C> // Another class that extends the base class, also has a child itself
public C setAmount(int amount) // method defined in class C

public class D extends C // Class that extends the previous one (C)
public E tapButtonTwo() // Method defined in class D, can't move this one level up to due to other parts of the code

Code that tries to use these classes and methods:

// Failing scenario
protected void doSomething() {
    // I already have an instance of type B, but I omitted this part
    b.tapButton() // returns type D
        .isLoaded() // returns type C and is the cause of the problem
        .setAmount(10) // returns type C
        .tapButtonTwo() // fails on: cannot resolve method
}

// Scenario that does work:
protected void doSomething() {
    // I already have an instance of type B, but I omitted this part
    b.tapButton() // returns type D
        .setAmount(10) // now returns type D
        .tapButtonTwo() // works
}
0

There are 0 best solutions below