Java 中的子类可以重写 set 方法并使参数类型更具体吗?

Can a subclass in Java override a set method and make the argument type more specific?

说我有一个 class

abstract class A {
    ArrayList<?> l;

    public void setList(ArrayList<?> l) //set the list
}

是否可以做类似的事情

class B extends A {
    public void setList(ArrayList<? extends Foo> l) //Set the list }

我基本上想指定一个带有参数化字段的抽象 class,其中从第一个 class 继承的 class 可以更具体地指定字段的类型,以便它必须扩展一些其他类型。

您需要将 A 设为通用:

abstract class A<T> {
  abstract void setList(List<? extends T> list);
}

然后让 B 变成这样:

class B extends A<Foo> {
  @Override void setList(List<? extends Foo> list) { ...}
}

如果你生成基数,它将起作用 class:

abstract class A<T> {
    ArrayList<T> l;

    public void setList(ArrayList<T> l) {//set the list
    }
}

class B<T extends Foo> extends A<T> {
    @Override
    public void setList(ArrayList<T> l) {//Set the list 
    }
}

Can a subclass in Java override a set method and make the argument type more specific?

没有。覆盖方法时,签名(名称和参数类型)在类型擦除后必须相同。有关详细信息,请参阅 JLS 8.4.2。

I basically would like to specify an abstract class with a parameterised field, where a class inheriting from the first class can specify the type of the field more specifically so that it must extend some other type.

abstract class A<T> {

    public abstract void setList(ArrayList<? extends T> l);
}

class B extends A<Integer> {

    @Override
    public void setList(ArrayList<? extends Integer> l) {

        //...
    };
}

此处编译器将执行类型擦除并且签名将相同。