We are about to switch to a new forum software. Until then we have removed the registration on this forum.
In processing the word new
initializes a new instance of an object, for instance
Cat myCat = new Cat()
Means make a new object, from the class Cat, which can be accesed by the name myCat.
Making a new object of the class Cat, means allocating memory to store all the variables in the class Cat, the location of this data, (its adress) is then stored at the variable myCat. At some point, the object cat, won't be used anymore (at the latest when the program is terminated), then the allocated memory must be freed, but you can't write in the code when, and how you want to do that.
In the programming language C++ , you will have to use the keyword delete
(or delete[]
) to delete each of the objects you initialized using new
. In C++ you also get to make a destructer-function when you make a class.
In processing you can't delete objects manually, so i asume, it happens automatically, but i would like to know how it works. And what about objects stored in other objects, or if more objects of the same or different class, are storring the same other object in them?
and are there a way to manually delete objects?
Answers
garbage collection is a complex subject. people write whole books about this stuff.
but basically there's a process that runs occasionally and anything that isn't still referenced can be reclaimed by it.
oracle tutorial about the java implementation - http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
http://docs.oracle.com/javase/8/docs/api/java/lang/ref/package-summary.html#reachability
In short, in order to "delete" an object, make sure its reference is completely "forgotten" from all variables & containers: https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
P.S.: We can also "suggest" to the garbage collector to make an extra effort to delete all claimable objects ASAP by issuing System.gc(): ;-)
http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#gc--
but System.gc() is too expensive to be calling all the time.
if it's a real problem then there are a lot of tuning options that may improve things. otherwise just let it do its thing and don't worry about it.