Kevin Jensen Petersen
Kevin Jensen Petersen

Reputation: 513

Adding object/class to a list with a different type

Basicly, I want to how if it's possible in Java to do following:

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?

Upvotes: 0

Views: 283

Answers (3)

Masudul
Masudul

Reputation: 21961

Your declaration should be ArrayList<? super Script>

Upvotes: 1

nanofarad
nanofarad

Reputation: 41281

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.

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

TestScript should be a subclass of 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.

Upvotes: 2

Related Questions