【问题标题】:Change type of ArrayList<Parent> to ArrayList<Child> when parent is abstract [duplicate]当父级为抽象时,将 ArrayList<Parent> 的类型更改为 ArrayList<Child> [重复]
【发布时间】:2016-06-15 05:45:54
【问题描述】:

我的问题是我有 2 个班级:父母和孩子。

父类是abstract,子类从它们扩展而来。

然后我有一个返回父 ArrayList 的方法,我需要将它转换为子的 ArrayList

我该怎么办?

【问题讨论】:

标签: java arraylist casting abstract


【解决方案1】:

感谢 Blackcompe

如果您使用的是列表实现的通用版本,则不需要强制转换,例如

ArrayList<BestTutor> list = null; 
BestTutor c = list.get(0); 

Generics 是一种类型安全方法,它告诉 Java 除了 BestTutor 之外什么都不会进入这个集合,所以你总是可以打赌 List.get() 将返回一个 BestTutor 或任何有界对象。 BestTutor 被称为有界对象。如果您不使用泛型,则有界对象是 Object.,例如

ArrayList<Object> list; 

虽然,这个边界是隐含的,所以它只是:

ArrayList list;

Java 将检查 computeArea 是否已被覆盖。如果有,它将使用该版本,否则它将使用继承的版本。例如

class Parent {
    void callMe(){
        System.out.println("Parent"); 
    } 
} 
class Child {
    void callMe(){
        System.out.println("Child");
    }
} 
Child c = new Child(); 
c.callMe(); //will display Child

它将调用 Parent 版本,该版本将打印 Parent,但我们覆盖了该方法。这是基本的覆盖。 Java也有多态性:

Parent p = new Child(); 
p.callMe(); //will display Child

Parent 类型的引用可以引用 Child 的实例。

如果您调用已被 Child 覆盖的 Parent 方法,Java 知道调用 Child 的实例方法,而不是 Parent 的。

有点高级,但在更高级的设计方法中会非常有用,比如"coding to interfaces"

【讨论】:

    【解决方案2】:

    您可以通过以下方式进行:

    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&lt;Parent&gt;List&lt;Child&gt; 不同。 Compilor 不允许将 List&lt;Parent&gt; 的引用分配给 List&lt;Child&gt;,即使 List 仅包含子对象。

    例如:

    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&lt;? super Child&gt; 的引用可以保证 List&lt;Parent&gt; 不会被损坏。

    【讨论】:

    • 它对我有用。非常感谢
    猜你喜欢
    • 2017-10-09
    • 2014-01-07
    • 2011-08-11
    • 2020-10-29
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多