Search code examples
javagenericsinner-classesbounded-types

How to define bound type parameters in Java inner class


public class TowerOfHanoi<E> {
    private class Disk<T extends Comparable<E>> {
    }

    private class Peg<S extends Disk<T extends Comparable<E>>> extends Stack<Disk<T extends Comparable<E>>> {
    }
}

With the above code, I'm getting the following compilation error.

Syntax error on token "extends", , expected

However, if I change the definition of Peg as follows, it works:

private class Peg<T extends Disk<? extends Comparable<E>>> extends Stack<Disk<? extends Comparable<E>>> {
}

I don't want to use a wildcard. Is there a way to change that to a named parameter?


Solution

  • You can't use generics like that. Simply pass the type (not the bound) to the extended type.

    This compiles:

    public class TowerOfHanoi<E> {
        private class Disk<T extends Comparable<E>> {
        }
    
        private class Peg<T extends Disk<Comparable<E>>> extends Stack<Disk<Comparable<E>>> {
        }
    }