Sunday 9 February 2014

Keyword : this

this” is a reference to the current object. i.e, by using “this” in any instance method or constructor, you can point out current object properties, behaviors and you can call current object constructors.

Example
class Person{
 String firstName, lastName;

 Person(String firstName, String lastName){
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public static void main(String args[]){
  Person p1 = new Person("Gopi", "Battu");
  System.out.println(p1.firstName +"\t"+p1.lastName);
 }
}


Output    
Gopi Battu


As you seen in the above example, constructor Person has parameter names as firstName, lastName which are same like instance properties of an object. So to differentiate parameters with instance properties we used the keyword “this”.

this can be used to call constructor
    Example
class Person{
 String firstName, lastName;

 Person(){
  this("noName", "noName");  // calls the constructor
 }

 Person(String firstName, String lastName){
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public static void main(String args[]){
  Person p1 = new Person();
  System.out.println(p1.firstName +"\t"+p1.lastName);
 }
}

Output
 noName noName
        
As you see in the above program, this is used to call the constructor.

Some Points to Remember
1. call to “this” must be first statement in constructor
     Example
class Person{
 String firstName, lastName;

 Person(){
  firstName = "HI";
  this("noName", "noName");
 }

 Person(String firstName, String lastName){
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public static void main(String args[]){
  Person p1 = new Person();
  System.out.println(p1.firstName +"\t"+p1.lastName);
 }
}

When you try to compile the above program, compiler throws below error
    
Person.java:7: error: call to this must be first statement in constructor
this("noName", "noName");
 ^
1 error
    
2. Calling this from any methods other than constructor causes compiler error         
class Person{
 Person(){

 }

 void setName(){
  this();
 }
}
         
When you try to compile the above program, compiler throws below error
Person.java:7: error: call to this must be first statement in constructor
     this();
     ^
     1 error

              
        

static blocks                                                 final keyword                                                 Home

No comments:

Post a Comment