javagenericsparameterized-types

What methods are possible to set an upper limit in with extend in Java


I just want to check that this is not possible/if it is possible with Java. I set-out to make a java version of template (i.e. a generic class) that could be used for a bounded string family.

    public abstract class BoundedNameType<U extends Integer> extends NameType
    {
         private static final   MAX_LEN = U;

         private BoundedNameTypes( final String... parameters ){

            super( MAX_LEN, parameters );

        }

    }//BoundedNameType

Where the parent class uses the U as a value for the MAX_LEN, e.g.

    public abstract class NameType
    {

         private NameType( final Integer u, final String... parameters ){

            this.maxLen = u;
        }

    }//NameType

Or perhaps go one better and make MAX_LEN is abstract protected, so I don't need a 'maxLen' member and the max value can always a static final. My efforts and reading indicate that generics in Java are types-only, so it shouldn't work. I've put links down, it is time to just use a declaration to do this; I would still like to know if there's a stricter generics way to do this!? Or that the definitive answer is "No".

See also:


Solution

  • That is not possible in Java. Generic parameters must be types.

    Java generics are only superficially similar to C++ templates.