Call subclass method from super class form

edited March 2017 in How To...

I am trying to make my own GUI (for fun and to learn), and I am using the parent-child method (currently a 1 way tree) for rendering and keeping components neat/together(parent moves, child moves with it). I hold my main GUI component that all my GUI components "extends" from, stored in an ArrayList of that. All my components use "Update()" to draw and function. My "GGUI"(head gui component to extend my components from) has an UpdateChildren() method, to call all the "Updates()" of the children (also in an "ArrayList").

How can I call the Update() method of the subclass for every component in the ArrayList - and I do not think using casting& conditional statements will help. I can loop through the list, however, I do not know how to access the subclass methods without casting. Another possible error that I do not know how to solve, is to skip a component if there is no "Update()" method found(so it doesn't stop the entire program, but just skip the problem- and maybe just delete it from the list)

Tagged:

Answers

  • Browsin' through answers and found this somewhat old one - I'll give it a shot, sorry if this is super late / useless.

    As long as it isn't a static, if I recall correctly, calling the superclass's method of a subclass method will still target the subclass method.

    You can use a try...catch... block to attempt running that component's update method... although if the component inherits a class with an update(), it will have one regardless. Your problem would only arise if you're using an array of Objects (Base base base class object), in which case you still have to cast anyways.

  • You can use an interface. Read about interfaces in Java.

Sign In or Register to comment.