子类含参数化类型的静态方法返回类型不兼容问题解析
静态方法返回泛型列表时的兼容性问题解析
问题背景
定义Parent和Child两个类,父类与子类均包含静态方法create()和createList():
Parent.java
import java.util.Arrays; import java.util.List; public class Parent { private final String name; public String getName() { return name; } public Parent(String name) { this.name = name; } static Parent create() { return new Parent("Parent"); } static List<Parent> createList() { return Arrays.asList(new Parent("Father"), new Parent("Mother")); } }
Child.java
import java.util.Arrays; import java.util.List; public class Child extends Parent { public Child(String name) { super(name); } static Child create() { return new Child("Child"); } static List<Child> createList() { return Arrays.asList(new Child("Brother"), new Child("Sister")); } }
此时编译器报错:The return type is incompatible with Parent.createList(),但create()方法可正常运行。
问题原因
- 静态方法的"重写"本质是隐藏:子类静态方法不会重写父类静态方法,而是隐藏父类方法,但Java仍要求返回类型满足兼容性规则。
- 非泛型返回类型的协变支持:
create()方法中,Child是Parent的子类,Java 5及以上支持协变返回类型,因此Child create()可合法隐藏Parent create()。 - 泛型的不变性限制:
List<Child>与List<Parent>是不变的——List<Child>并非List<Parent>的子类,无法满足静态方法隐藏时的返回类型兼容性要求,导致编译报错。
解决方法
使用带通配符的泛型返回类型List<? extends T>,利用泛型协变性满足兼容性:
修改后的Parent类createList方法
static List<? extends Parent> createList() { return Arrays.asList(new Parent("father"), new Parent("mother")); }
修改后的Child类createList方法
static List<? extends Child> createList() { return Arrays.asList(new Child("son"), new Child("daughter")); }
扩展到Grandchild类
static List<? extends GrandChild> createList() { return Arrays.asList(new GrandChild("grandson"), new GrandChild("granddaughter")); }
使用示例
// 直接接收返回值 { List<? extends Child> childList = Child.createList(); childList.forEach(System.out::println); } // 转换为具体类型列表 { List<Child> childList = new ArrayList<>(); childList.addAll(Child.createList()); childList.forEach(System.out::println); }
内容的提问来源于stack exchange,提问作者Eliezer Garza
相关产品推荐
相关产品推荐

