1

Using raw types for generics, the bounds get ignored, too. However only the bounds of the highest level class. The parent class keeps its bounds. This seems like inconsistent behaviour.

public class GenericType
{
    public static void main(String[] args)
    {
        ExampleExtended<?> example1 = null;
        ExampleExtended example2 = null;

        Integer result1 = example1.get();
        Number result2 = example2.get();
    }
}

abstract class GenericExample<C extends Number>
{
    public abstract C get();
}

abstract class ExampleExtended<C extends Integer> extends GenericExample<C>
{
}

The expected return type of example2.get() is Integer, due to the defined bounds of ExampleExtended, as it is the case for "example1" with a wildcard. However, it seems due to the raw type, for some reason, the bounds are ignored and the return type is NOT Integer.

Now you would expect the return type to be "Object". Since the bounds of ExampleExtended are ignored it would be consistent if they are ignored for GenericExample as well, after all. This is NOT the case, either! The return type is Number!

Why? This seems so oddly inconsistent to me.

  • Because with raw types you opt out of using generics at all. – Seelenvirtuose Jun 09 '19 at 11:47
  • @Seelenvirtuose Then the return type should be of type Object, and not Number. As I have written in my question, the bounds of the parent class are preserved. – TomHardlyACT Jun 09 '19 at 12:04
  • 1
    The relevant quote from [JLS 4.8](https://docs.oracle.com/javase/specs/jls/se12/html/jls-4.html#jls-4.8) is "The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C." Because `get` is declared with a bound of `Number`, that its return type when used in a raw context. – Andy Turner Jun 09 '19 at 13:41
  • @AndyTurner Thanks for the exact quote. It is difficult to understand the JLS when English is not your mother tongue due to it be written like a law book. It still leaves out the question why exactly this is, as it is still inconsistent error prone behaviour, imo. However the more I read into this topic, I understand that raw types are an unwanted half-hearted implemented feature since Generics were introduced that should not be used. – TomHardlyACT Jun 09 '19 at 14:16
  • 2
    @TomHardlyACT English is my mother tongue, and it's still pretty hard to read at times. – Andy Turner Jun 09 '19 at 14:17

0 Answers0