Does the finalize () method of a java class do exactly the same as the ondestroy () method for android?

0

It's really funny, since the finalized method in the object class does cleaning tasks before the object has been deleted from memory, which is also done by the onDestroy class.

So I have this question in which they differ and why for Android developers decided to implement onDestroy() if you already had finalize() .

I am investigating about it but what do you think.

    
asked by FuriosoJack 14.12.2016 в 21:44
source

2 answers

2

You can say they are similar:

  • The onDestroy() method is called when the Activity is finished and is performed before destroying the Activity , either because the finish() method is called or because the operating system requires memory.

  • The finalize() method is called when the object is finalized by the GC.

They are similar because: in both methods you can perform actions before the Activity or the Object is destroyed.

The difference is: finalize () is called by the garbage collector (Gargage Collector) while onDestroy () is called when the method finish () is executed or because the system is temporarily destroying this instance of the activity to save memory. **

From the documentation:

  

finalize () Call by garbage collector (Gargage Collector) of an object when the   collection of unused items determines that there is no more   references to the object.

     

onDestroy () The last call you receive before the activity be   destroyed. This can happen either because the activity is   ending (someone called finish () or because the system is   temporarily destroying this instance of the activity to save   memory. You can distinguish these two scenarios with the method   isFinishing ().

The finalize() method for an Activity exists, but remember something important, do not try to be smarter than the Garbage Collector, since he will decide when to remove the instance. I mention it because it was previously common see this call to try to free memory ⤜ (ʘ_ʘ) ⤏, also its execution is determined by the Garbage Collector.

    
answered by 14.12.2016 / 22:27
source
1

When the onDestroy method is executed in an android application there are 2 reasons

  • Someone (or Something) called finish() of Activity
  • The operating system needs to free memory.

When the finalize() method is executed, the exact same thing happens (Need to free memory or not identify references to the object in question) but it is called by the collector. Eye, that there is no way to know when garbage collector is going to call the function finalize() and if you need to use this method very probably there is something wrong in its logic and code. If executed, the collector is responsible.

Both methods can overwrite them and add code to know or see when your object is going to be destroyed.

    
answered by 14.12.2016 в 22:35