Why does erasure still allow overriding/implementation?
javac
actually creates bridge methods for this:
class Impl implements Test<Integer>{
@Override public Integer getValue(Integer n){
return n;
}
}
compiles to
class Impl implements Test {
public Integer getValue(Integer n) { // overrides nothing!
return n;
}
@Override @Synthetic @Bridge public Object getValue(Object n) {
return this.getValue((Integer)n);
}
}
Note: Synthetic
and Bridge
are not real annotations, but the compiled class files do tag these methods as "synthetic" and "bridge".
By using these bridge methods, Java ensures that if you have an Impl
, you can call Impl#getValue(Integer)Integer
(if you know that it actually has type Impl
), or you can call the "generic" Test#getValue(Object)Object
, if you only know that it's a Test<?>
.