The this keyword

Posted By on September 9, 2014

Download PDF
Method overriding
loops in java

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object.That is, this is always a reference to the object on which the method was invoked.

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

To better understand what this refers to, consider the following version of RectDemo( ):

RectDemo(int length, int breadth)
this.length = length;
this.breadth = breadth;

This version of RectDemo( )  operates exactly like the earlier version.  Inside RectDemo( ),  ‘this ‘ will always refer to the invoking object.

Use “this” to overcome Instance Variable Hiding.

As you know, it is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. Interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables.

However,  when a local variable has the same name as an instance variable,  the local variable hides the instance variable. This is why  length and breadth  were not used as the names of the parameters to the RectDemo( ) constructor inside the RectDemo class.

If they had been, then length would have referred to the formal parameter, hiding the instance variable length. While it is usually easier to simply use different names, there is another way around this situation. Because this  lets you refer directly to the object, you can  use it to resolve any name space collisions  that might occur between instance variables and local variables. For example, here is another version of  RectDemo( ), which uses  length and breadth  for parameter names and then uses this to access the instance variables by the same name.

Method overriding
loops in java

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby