It is really something curious, since the finalize method by default in the object class does cleanup tasks before the object is removed from memory, which is something that the onDestroy class also does.
So that doubt arises in me in what they differ and why for the android developers they decided to implement onDestroy()
if they already had it finalize()
.
I'm looking into it but what do you guys think?
They can be said to be similar:
The method
onDestroy()
is called when the Activity is finished and is done before destroying theActivity
, either because the method was calledfinish()
or because the operating system requires memory.The method
finalize()
is called when the object is finished by the GC.They are similar because: in both methods you can perform actions before the Activity or Object is destroyed.
The difference is: finalize() is called by the Gargage Collector while onDestroy() is called when the method is executed
finish ()
or because the system is temporarily destroying this instance of the activity to save memory.**From the documentation:
The method
finalize()
for an Activity exists, but remember one important thing, don't try to outsmart the Garbage Collector, as it will decide when to remove the instance. I mention it because previously it was common to see this call to try to free memory ⤜(ʘ_ʘ)⤏, also its execution is determined by the Garbage Collector.When the method
onDestroy
is executed in an android application there are 2 reasonsfinish()
theActivity
When the method is executed
finalize()
exactly the same thing happens (need to free memory or not identify references to the object in question) but it is called by the collector. Note that there is no way to know when garbage collector is going to call the functionfinalize()
and if you need to use this method there is most likely something wrong with your logic and code. Executing it is handled by the collector.Both methods you can override and add code to know or see when your object is going to be destroyed.