简体   繁体   English

Java中具有类型擦除的重写/重载方法

[英]overriding / overloading methods with type erasure in java

with the given 2 classes: 给定2类:

public class A{
    public <T> Cell<T> f(Cell<T> l){
        return null;
    }
}
public class B extends A{
    public <T> Cell<T> f(Cell<Cell<T>> l){ // trying to override
        return null;
    }
}

(when Cell is some generic class). (当Cell是某个通用类时)。

i understand that after type erasure, the classes looks like: 我知道类型擦除后,类看起来像:

public class A{
    public Cell f(Cell l){
        return null;
    }
}
public class B extends A{
    public Cell f(Cell l){ // trying to override
        return null;
    }
}

before i knew the type erasure thing, i think that i did understand why the compiler sees it as an overloading. 在我知道类型擦除之前,我认为我确实理解了为什么编译器将其视为重载。

but now that i (think that) i know about the type erasure, the two method signatures are the same, and i really think that it makes much more sense that the compiler will see this as an OVERRIDING. 但是现在我(认为)我知道类型擦除,这两个方法签名是相同的,而且我真的认为编译器将其视为覆盖更为有意义。

after compiling it, got that java's compiler saw this as a trying to OVERLOAD and not override, and yields an error for overloading to identical-signatured methods. 编译之后,得到了Java的编译器将其视为OVERLOAD的尝试,而不是覆盖,并因重载到相同签名的方法而产生错误。

my question : why the compiler still sees this as a trying of OVERLOADING and not OVERRIDING, although after type erasure the signatures are just the same? 我的问题 :尽管类型擦除之后,签名仍然相同,但为什么编译器仍将其视为重载而不是重载?

thanks! 谢谢!

The error "overloading with same signature" seems adequate here. 错误“具有相同签名的重载”在这里似乎足够。 It is not technically overriding because to the compiler generics matter and B's f does not satisfies A's signature as A's f T is not restricted to implement Cell<?> so B's f is not overriding A's f; 从技术上讲,这不是最重要的,因为对于编译器泛型而言很重要,并且B的f不满足A的签名,因为A的f T不限于实现Cell<?>因此B的f不会取代A的f。 it makes more sense to call it "overloading" instead because generic-wise those signatures are different despite end up being the same after erasure. 取而代之的是将其称为“重载”,因为从通用角度来看,尽管在擦除后最终相同,但这些签名却是不同的。

I reckon that the "overloading with same signature" error was added for this particular scenario with generics resulting in conflicting erasures. 我认为,针对这种特殊情况使用泛型添加了“具有相同签名的重载”错误,导致擦除冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM