Why erasure of generic types prevents overriding in this case?

Viewed 107

The code below doesn't compile on OpenjDK 11. It seems to me that test1 in B should override test1 in A, because:

  1. The methods have same name.
  2. The methods have same parameter list.
  3. The methods have same visibility.
  4. The methods actually do not throw potentially incompatible checked exceptions.
  5. Their return types are covariant.

I took a decompiler and decompiled each class separately. The compiled code actually worked as I would expect. It replaced U extends Number with Number, T extends Integer with Integer and so on. But when I try to compile the two classes together, I got and error on the second class that says the test in the second class does not override a method in the first one.

I'm missing something big or small here. And it's probably related to 5. Maybe the types are not covariant. Can you help me?

class A {
    <U extends Number, T extends Number> U test(T test) {
        System.out.println("In A.test(T test)");
        return null;
    }
    //Decompiler shows that the above method erases to 
    // Number test(Number test)
    // Just like the method below.
        
    Number test2(Number test) {
        return null;
    }
}

class B extends A {
    //Unsuccessful override. Compiler error.
    @Override  
    <U extends Integer, T extends Number> U test(T test) {
        System.out.println("In B.test(T tesT)");
        return null;
    }
    //Decompiler shows that the above method erases to 
    //Integer test(Number test)
    //Just like the method bellow.
    
    
    //Successful override
    @Override
    Integer test2(Number test) {
        return null;
    }
}
2 Answers

The reason why your test methods produce an error is because they have totally unrelated, different signatures. Note that the signature of a method consists of its name, parameter list, and type parameters.

Quote from the Java Language Specification:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the type parameters of M, the same formal parameter types.

Crucially, your two test methods do not have the same type parameters, because U in A.test has a different bound from U in B.test.

Two methods or constructors M and N have the same type parameters if both of the following are true:

  • M and N have same number of type parameters (possibly zero).

  • Where A1, ..., An are the type parameters of M and B1, ..., Bn are the type parameters of N, let θ=[B1:=A1, ..., Bn:=An]. Then, for all i (1 ≤ i ≤ n), the bound of Ai is the same type as θ applied to the bound of Bi.

Think about what would happen if B.test actually overrode A.test. You could pass a type to the type parameter U that is out of its bounds!

A a = new B();
// This will call B.test, and U is Double, T is Integer
// but U should extends Integer!
Double x = a.test((Integer)0); 

For more info, here are the precise rules for when overriding happens. Note that criteria #4 and #5 on your list are not actually considered. They are just additional requirements that make your code not compile if you break them. One method is still "defined" to override another even if you break those requirements. They are listed here in the JLS.

Given that I find the relevant JLS rules (cited in Sweeper's answer above) quite confusing, it's useful to mention the rules, as formulated by the great people at Enthuware (https://enthuware.com/). They don't mention the visibility and exceptions rules, but they go in detail with Generics. And they seem to explain my two cases, mentioned in the comments above. I'll just state the cases again here:

class A {
    public <T,U> U test(T test) {
        return null;
    }
}

class B extends A {
    //Successful override even though type parameters do not match
    //This method even has none.
    @Override
    public Number test(Object test) {
        return null;
    }
}

class C {
    public Object test(Object test) {
        return null;
    }
}

class D extends C {
    //Same situation as A and B, but with places being exchanged.
    //Now the generic method overrides non-generic. 
    //And we have error. 
    @Override
    public <T,U> U test(T test) {
        return null;
    }
}

Now the steps, as formulated by Enthuware:

Steps to check for valid override:

First, check the method signature (i.e. method name and the parameter list). If the signature of the method in the subclass matches the signature of the method in the super class, then it could be a valid override, otherwise it is just an overloaded method. Note that signature does not include parameter names and parameter's generic type specification.

NOTE: I think they mean for us to replace the type parameter with its bound and then compare both methods.

Second, if it is a potential override, check the generic type specification of the parameters. If the overriding method does not use a generic type specification for the parameter type, then it is valid. The reverse is not valid i.e. the overriding method is allowed to erase the generic type specification but is not allowed to add a generic type specification if the overridden method does not have it. If both the methods have a generic type specification, then the specification must match exactly. For example, if the overridden method has Set<Integer>, then the overriding method can use Set or Set<Integer>. But if overridden method has Set, then the overriding method must also have Set for a valid override.

Third, if it is a potential override, check the return type. Java allows "covariant" returns, which means, the return type of the overriding method must be the same or be a subtype of the return type mentioned in the overridden method. Check the two return types without the generic type specification. If return type of the overriding method is covariant with respect to the return type of the overriding method (for example, ArrayList is covariant with List), then perform the same check including the generic type specification (for example, ArrayList<CharSequence> is covariant with List<? extends CharSequence>). Don't get confused by the presence of <T> in the code. The same rules of overriding still apply. The T in <T> is called as the "type" parameter. It is used as a place holder for whatever type is actually used while invoking the method. For example, if you call the method <T> List<T> transform(List<T> list) with List<String>, T will be typed to String. Thus, it will return List<String>. If, in another place, you call the same method with Integer, T will be typed to Integer and therefore, the return type of the method for that invocation will be List<Integer>

Related