This keyword:
Whenever it is
required to point an object from a functionality which is under execution
because of that object, then we use the ‘this’ keyword.
The job of this keyword is only to
point.It is always points to an object that is executing the block in which
‘this’ keyword is present. In a nut-shell this keyword points to the current
object.
Example:
Class A
{
Int
i;
A(int
i)
{
This.i=
i+1;
i=i+1;
system.out.println (i);
}
Void function ()
{
int
i=67;
sysyem.out.println
(i);
sysyem.out.println (this. i);
this.i= this.i+1;
}
Public static void main (String
args[])
{
A
a= new A( 6);
sysyem.out.println (a.i);
a.function
();
sysyem.out.println
(a.i);
//this.i=203;
}
}
Note: this operator points to address of
the instance. It will never points to the context of the class.
We know that static functions are not
executed with the address of the instance even though we call then using it.
that is why ‘this’ operator works only in non-static blocks. It will not work
in static blocks.
·
Constructor
is a non-static block, that is why we are able to use ‘this’ operator inside a
constructor.
·
We
can call a constructor explicitly, without creating another object of that
class only through a constructor.
·
We
can’t constructor through functions.
Uses of this operator:
1. To point a constructor of a class
from the constructor of the same class.
2. To point current object from the
non-static blocks .
No comments:
Post a Comment