简体   繁体   中英

Generics method overriding 8

Why can't void say(List< ? extends Number> list) be overridden by void say(List< Number> list) .

Name clash occurs when you try to compile.

You cannot override a method declared as

void say(List<? extends Number> list)   // A

with

void say(List<Number> list)             // B

simply because the types are not equivalent. For example, List<Integer> matches List<? extends Number> List<? extends Number> but not List<Number> , so

List<Integer> integers = Arrays.<Integer>asList(1, 2, 3);
a.say(integers);  // is valid assuming signature A
b.say(integers);  // does not compile

(see this question for details about generics, wildcards, and type relationships ). If the compiler did allow you to override the way you want to, then the following would be possible:

class A {
    void say(List<? extends Number> numbers) { }
}

class B extends A {
    void say(List<Number> numbers) { numbers.add(Double.valueOf(1.0)); }
}


List<Integer> onlyIntsPlease = new ArrayList<Integer>();
B b = new B();

// Oops! The list of `Integer` will now contain a `Double`...
b.say(onlyIntsPlease);

This is impossible both on general theoretical grounds and due to the specifics of Java Generics.

The general principle is that the overriding method must be substitutable for the base class method. For example, the subclass method may use a wider access modifier, but not a narrower one. In your case,

void say(List<Number> list)

is more constraining than

void say(List<? extends Number> list) 

so this clearly violates the substitutability principle.

A practical obstacle is this: overriding is about runtime polymorphism, whereas Generics are about compile-time polymorphism and the type parameters of the instance are not even available to the method dispatch mechanism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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