This has been solved! Look at the end of this post.
I'm having some trouble here with polymorphism, as I need to access methods in a subclass from an array of superclass objects.

This method is called parseCommand(Command c);
The method exists in the superclass and is overridden in the subclasses.

I'm using a LinkedList<Entity> with all the entities in the game.
There are (Will be) several objects of a class in this list which extends entity. The issue here is that I want to be able to access the parseCommand method in the subclass, not in the entity class.
I can do this with a simple typecast, like this:

((MySubClass)targetEntity).parseCommand(new Command(input,parameter));

However, I'm using multiple subclasses in this LinkedList<Entity> collection. I want to be able to do something in the lines of:

subclass.targetEntity.parseCommand(new Command(input,parameter));

Is there a way to do this?


Looks like it was a logical error on my end! It works exactly as I intended, it seems to use the override in the subclass automatically.
If you came here for the same reason as me, assume it works and see if you can find any errors beyond the scope of typecasting issues.

As long as the method is not static, you will be using whichever one is most appropriate to the object it is being called on. I.E. if the same method is declared in that object it will use that one, otherwise it will use the one from its super class, otherwise its super classes super class, etc, etc. All of this based from the actual objects type, not the type of the reference. I.E.

Object o = new String("a");

will print "a" and not "Object@xxxxxxx" because it is using Strings version of toString() and not Objects version of toString().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.