Java Generics: Why I get "name clash" exception when I override methods with different "type" parameter ?
import java.util.*; class Parent { void foo(List<String> list) { System.out.println("parent"); } } class Child extends Parent { void foo(List<Integer> list) { System.out.println("child"); } }
When you compile this code you will get an error like
Parent.java:7: name clash: foo(java.util.List<java.lang.Integer>) in Child and foo(java.util.List<java.lang.String>) in
Parent have the same erasure, yet neither overrides the other
class Child extends Parent {
^
1 error
This "name clash" error thrown because of "type erasure" thing when "generics" code gets complied.
Let’s see how,
When we complied any generics code, the compiler removes the type from the code and treat it as a simple pre Java 1.5 code, like, in our case, compiler saw something like this,
import java.util.*; class Parent { void foo(List list) { // oops, <String> get erased. System.out.println("parent"); } } class Child extends Parent { void foo(List list) { // same here System.out.println("child"); } }
And all this is because of "Type Erasure", and that’s forced compiler to think Child's method "foo" as a overloading of parent’s class "foo" and NOT overriding. Overriding the method would be violating the type check for the Parent class and overloading with the same signature throws an error.
Comments