0

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?

1
  • Have you tried to run your code? Why ask us if it works? Commented Nov 2, 2013 at 18:49

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It is already mentioned in the question, that TestScript extends Script. See line #2 of his code snippet.
The question may be calling TestScript methods on the elements.
Exactly. My TestScript extends Script, which in theory should work, but doesn't. Can it be something to do, that my script above, which is a "ScriptManager" is in a subfolder, but the TestScript is in the root?
1

Your declaration should be ArrayList<? super Script>

2 Comments

I wouldn't say should.
Masud: No, it won't work. Try it. Adding TestScript instances won't work, since it could be an ArrayList<FooScript> where FooScript extends Script but not TestScript.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.