Reputation: 513
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
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
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