简体   繁体   English

将对象/类添加到具有不同类型的列表中

[英]Adding object/class to a list with a different type

Basicly, I want to how if it's possible in Java to do following: 基本上,我想知道如何在Java中执行以下操作:

public static ArrayList<Script> scripts = new ArrayList<Script>();
scripts.add(new TestScript()); //TestScript extends Script class.

I've tried some different things with type casting, and asking some of my friends. 我用类型转换尝试了一些不同的事情,并问了我的一些朋友。 No one seem to have an answer. 似乎没人能回答。 But I know it would be possible.. maybe? 但是我知道这是可能的..也许吗? If so, how do I make the above work? 如果是这样,我如何进行上述工作? If it doesn't, what else can I do to get the same effect? 如果没有,我还能做些什么来获得相同的效果?

TestScript should be a subclass of Script . TestScript应该是Script的子类。 A collection of an object can hold the objects of the same class and all of its subclasses. 一个对象的集合可以保存相同类及其所有子类的对象。

No casting is required because TestScript is logically a Script as it extends from Script. 从逻辑上讲,TestScript在逻辑上是一个脚本,因此不需要强制转换。

Your declaration should be ArrayList<? super Script> 您的声明应为ArrayList<? super Script> ArrayList<? super Script>

Yes, this will work. 是的,这将起作用。 You'll do as follows: 您将执行以下操作:

public static ArrayList<Script> scripts = new ArrayList<Script>();
scripts.add(new TestScript()); //TestScript extends Script class.

and to traverse, 并遍历

for( Script scr : scripts){
    scr.someMethodOfScript(); //no testscript methods available
    if(scr instanceof TestScript){
        TestScript tscr = (TestScript) scr;
        //call TestScript methods on tscr
    }
}

You'll need an instanceof and a cast for any TestScript methods not available in Script. 对于Script中不可用的任何TestScript方法,您将需要一个instanceof和一个强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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