Saturday, 26 July 2014

Usage of "this" operator in Java

The this keyword is a reference to the current object.
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:

class Employee
{
    private int age;

    public Employee(int age)
    {
        my.age = age;
    }
}


First lets take a look on code
public class Employee  {

private int empId;
private String name;

public int getEmpId() {
    return this.empId;
}

public String getName() {
    return this.name;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

public void setName(String name) {
    this.name = name;
}
}
In the above method getName() return instance variable name. Now lets take another look of similar code is
public class Employee  {

private int empId;
private String name;

public int getEmpId() {
    return this.empId;
}

public String getName() {

    String name="Yasir Shabbir";
    return name;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

public void setName(String name) {
    this.name = name;
}


public static void main(String []args){
    Employee e=new Employee();
    e.setName("Programmer of UOS");

    System.out.println(e.getName());

}
}
Output Yasir Shabbir
  • this operator always work with instance variable(Belong to Object) not any class variable(Belong to Class)
  • this always refer to class non static attribute not any other parameter or local variable.
  • this always use in non static method
  • this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the same name as a field of the class. In this case, use reference this if you wish to access the field of the class—otherwise, the method parameter or local variable will be referenced.









No comments:

Post a Comment