<分区>
我的问题是我有 2 个类:父类和子类。
父类是抽象的
,子类是从它们扩展而来的。
然后我有一个返回父级 ArrayList
的方法,我需要将它转换为子级的 ArrayList
。
我该怎么办?
<分区>
我的问题是我有 2 个类:父类和子类。
父类是抽象的
,子类是从它们扩展而来的。
然后我有一个返回父级 ArrayList
的方法,我需要将它转换为子级的 ArrayList
。
我该怎么办?
最佳答案
您可以通过以下方式:
import java.util.ArrayList;
import java.util.List;
abstract class Parent {
void callMe(){
System.out.println("Parent");
}
}
class Child extends Parent {
void callMe(){
System.out.println("Child");
}
}
public class TestClass {
public static void main(String[] args) {
List<Parent> alist=new ArrayList<Parent>();
List<? super Child> alist2=alist;
}
}
List<Parent>
与 List<Child>
不同.编译器不允许分配 List<Parent>
的引用至 List<Child>
即使列表仅包含子对象。
例如:
List<Parent> parentList=new ArryList<Parent>();
parentList.add(new Child());
parentList.add(new Child());
parentList.add(new Child());
//This is not allowed
List<Child> childList=(List<Child>)parentList;//Compiler Error
//But,This is allowed
List<? super Child> childList=parentList; //Okey
这是允许的,因为使用了 List<? super Child>
的引用保证 List<Parent>
不会被破坏。
关于java - 当父级为抽象时,将 ArrayList<Parent> 的类型更改为 ArrayList<Child>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746107/
相关文章:
c++ - clang 编译的程序在 std::any_cast 期间抛出 std::bad_any_cast
java - 在 Derby 中将主键列类型从 Integer 迁移到 BigInt
Java 两个不同的文档,完成了一些东西,但现在它们是一个..希望它们分开
ios - 无法将类型 'UIView' 的值分配给类型 --class 符合 UIView--
ios - 如何将持有 int 的 iOS id 类型转换为 NSString?
java - 修复 GUI 输出,将 2 个 JPanel 添加到单个 JFrame