Overriding generic methods with non-generic implementations

后端 未结 2 1550
傲寒
傲寒 2021-01-03 03:48

I\'m experimenting with generics in Java, and thought of this example.

If I have ClassA, I can override it with a subclass that references a co

相关标签:
2条回答
  • 2021-01-03 04:22

    Thanks to type erasure, this:

    public <T> void doSomething(T data);
    

    Really means this:

    public void doSomething(Object data);
    

    So no, there isn't a way to override with a more restrictive parameter type.

    Also in this code:

    class ClassA<T> {
        public <T> void doSomething(T data) {};
    }
    

    The type parameter in your class name and the type parameter in the method are actually different parameters. It's like declaring a local variable of the same name as a variable in a higher scope. You can call doSomething(123) on an instance of ClassA<String> because the second T is local to the method.

    0 讨论(0)
  • 2021-01-03 04:36

    In short, the the answer is no. If you define a method with a generic parameter, then its signature contains a the generic and any "overrides" would have to match the signature (contain a generic).

    Anyhow, this really is a poor use of generics, as what you've written is semantically the same as

    public void doSomething(Object data) {}
    

    The generic bit doesn't buy you much unless is it being used to indicate what the return value would be, as in:

    public <T> T doSomething(T data) {}
    

    But why bother? Is there really an issue calling doSomething() generically?

    0 讨论(0)
提交回复
热议问题