Wednesday, January 20, 2016

Topic 13: this and finalize in Java

The this Keyword


  • this is always a reference to the object on which the method was invoked

  • We can use this anywhere a reference to an object of the current class’ type is permitted

 

Instance Variable Hiding

  • As we know, it is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. However, we can have local variables and/or parameters to methods with names similar to instance variables. 

  • When a local variable has the same name as an instance variable, the local variable hides the instance variable

    class Box
    {
    double width, height, depth;

    Box(double width, double height, double depth)
    {
    // Here the instance variables are not initialized because the local variable hides the instance variable
    width = width;
    height = height;
    depth = depth;

    }

  • this refers directly to the object. We can use it to resolve any name space collisions between instance and local variables. For ex:

Box(double width, double height, double depth)
{
// Here the instance variables are initialized because of this keyword
this.width = width;
this.height = height;
this.depth = depth;

}

 

Garbage Collection


Java handles deallocation automatically using garbage collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. Garbage collection only occurs sporadically (if at all) during the execution of our program.


The finalize( ) Method


  • By using finalization, we can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector

  • To add a finalizer to a class, we simply define the finalize( ) method

  • The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, we will specify those actions that must be performed before an object is destroyed.

  • The finalize( ) method has this general form:

    protected void finalize( )
    {
    // finalization code here
    }

Important note: finalize( ) is only called just prior to garbage collection. We cannot know when—or even if—finalize( ) will be executed. Therefore, our program should provide other means of releasing system resources, etc., used by the object.


Click for NEXT article.


Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment