Matthew Patience wrote: > I have a class called "Laser". It's basically just a laser shot that > moves across the screen. What I want to do is while the user is > holding down the fire button to have it keep creating instances of the > Laser class like a rapid fire and then when they hit the edge of the > screen have them be disappear/destroyed so they are no longer taking > up memory. My problem is I have no idea how to have it keep creating > instances of a class without explicitly naming them like: > > laser1 = new Laser(getContext(), R.drawable.laser); > laser2 = new Laser(getContext(), R.drawable.laser); > laser3 = new Laser(getContext(), R.drawable.laser); > laser4 = new Laser(getContext(), R.drawable.laser); > laser5 = new Laser(getContext(), R.drawable.laser);
An instance of the Laser class is an object. You can hold onto those in local variables. You can hold onto those in data members. You can pass them as parameters to methods. You can return them as results from methods. So, somewhere along the line, after you create the Laser object, you are doing something with it. After all, it is not going to "move across the screen" by its little ol' lonesome. Either something is using the information in a Laser object to draw it, or a Laser knows how to draw itself. If something is drawing the Laser instances on the screen, have it manage the Laser objects (e.g., hold them in an ArrayList<> and remove them from the list when they are no longer needed). If Laser instances are drawing themselves, then whoever called new Laser(...) should be holding onto them as long as they are relevant (e.g., in an ArrayList<>) and letting go of them when they are done. > Also I don't know how to destroy an instance of a class as well. Any > ideas? You don't "destroy an instance of a class" in Java. You let go of all references to it, and it gets garbage collected. "Unlike in many other object-oriented programming languages, Java performs automatic garbage collection - any unreferenced objects are automatically erased from memory - and prohibits the user from manually destroying objects." http://en.wikibooks.org/wiki/Java_Programming/Destroying_Objects -- Mark Murphy (a Commons Guy) http://commonsware.com | http://twitter.com/commonsguy Android Development Wiki: http://wiki.andmob.org -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en To unsubscribe, reply using "remove me" as the subject.

