First use
It refers to the current object
example
class test
{
private int number = 20 ;
void show ( int number )
{
System.out.println ("Local variable " + number ) ; // prints 10
System.out.println ("Object property " + this.number ) ; // prints 20
} // function ends
public static void main ( String args [ ] )
{
test one = new test ( ) ;
one.show (10) ;
} // main function ends
} // class ends
- In the function show , when we use number it refers to the local variable,
hiding object property number - If we want to access the object property number , we have to use this
Second use
It can be used to call an overloaded constructor
example
class Student
{
String name ;
int age ;
Student ( )
{
}
Student ( String input1 )
{
name = input1 ;
}
Student ( String input1 , int input2 )
{
this ( input1 ) ; // call second constructor to initialize name of student
age = input2 ;
}
public static void main ( String args [ ] )
{
Student one = new Student ( "Harry" , 20 ) ;
System.out.println ("Name : " + one.name + " , age : " + one.age ) ;
} // main function ends
} // class ends
Output: Name : Harry , age : 20
Third constructor calls the second one using this and passes the input1 value which is set to name inside second constructor
Advantage is that each constructor does not need to initialize all
the properties itself. It calls the appropriate overloaded form by
passing the needed values.