Search This Blog

Monday, March 14, 2011

this Keyword In Java

All java developer aware role of 'this'. 'this' is a reference to the current object in constructor and instance methods.

In java we use 'this' in different place are:

  1. Using 'this field' inside constructor/non-static method.

  2. Using 'this field' inside static method.

  3. Using this() method inside constructor

  4. Using this() method inside static/non-static methods.

  5. Recursive constructor invocation using this().


S.No.



Place
of 'this'



Description



When
executes



Where
Not Include



Sample
Code



1



Using
'this field' inside constructor/non-static method



'this'
act as the reference to the current object, So using 'this' we can
access the class instance variable and methods(static/no-static).


Most
of the case we use in POJO class setter & getter method.



We
can use to refer the current object instance variable inside the
constructor/non-static methods.



Its should
be used anywhere in inside constructor/non-static method.



package
thispck;


public
class
SampleThis


{ int
intvalue;


public
SampleThis(
int
intvalue)


{


this.intvalue=intvalue;


}


public
static
void
main(String arg[])


{


SampleThis
sampleThis=
new
SampleThis(10);


System.out.println("Int
Value::"
+sampleThis.intvalue);


}


}


Output:


Int
Value::10



2



Using
'this field' inside static method.



Not
possible to use this.



-



Compile
time error.


Error:


cannot use
this in a static context.



-



3



Using
'this() method' inside constructor



This()
method used for calling the default constructor and parameter
constructor in a class.






While
object creation using new keyword.



'this()'
declaration should be first statement in constructor.


Otherwise
compile time Error:


Constructor
call must be first statement in constructor






package
thispck;


public
class
SampleThis


{ int
intvalue;


public
SampleThis(
int
intvalue)


{


this.intvalue=intvalue;


}


public
SampleThis()


{


this(0);


}


public
static
void
main(String arg[])


{


SampleThis
sampleThis=
new
SampleThis(10);


System.out.println("Int
Value::"
+sampleThis.intvalue);


}


}


output:


Int
Value::10



4



Using
this() method inside static/non-static methods.



Compile
time error



-



Error:


Constructor
call must be the first statement in a constructor



-



5




Recursive constructor
invocation


using
this()



Compile
time error



-




Compile
time error.



public
SampleThis(int intvalue)



{



this();



this.intvalue=intvalue;



}







public
SampleThis()



{



this(0);



}



package
thispck;


public
class
SampleThis


{ int
intvalue;


public
SampleThis(
int
intvalue)


{


this();


this.intvalue=intvalue;


}


public
SampleThis()


{


this(0);


}


public
static
void
main(String arg[])


{


SampleThis
sampleThis=
new
SampleThis(10);


System.out.println("Int
Value::"
+sampleThis.intvalue);


}


}


No comments:

Post a Comment