6

Is using the keyword this optional in Java? Or do I have to use it? And when it is not optional? In the following code it does not affect my application, regardless of how many instances of Employee I made. The print method prints Employee details without anything wrong even if details do not match.

public class Employee {
    String name;
    int Salary;
    int pension;
    String workPlace;
    String teleNo;
    int age;

    void printDetails(){
        System.out.println("Name is :  "+this.name );
        System.out.println("age is  :  "+this.age );
        System.out.println("WorkPlace is  :  "+this.workPlace );
        System.out.println("Salary is  :  "+Salary );
        System.out.println("Pension is  :  "+this.pension );
        System.out.println("Telephone No. is  :  "+this.teleNo );
        System.out.println("age is  :  "+Integer.toString(age) );
    }
}

public class Main extends Employee {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Employee obj=new Employee();
        obj.age=25;
        obj.name="Yasser";
        obj.pension=100_000;
        obj.teleNo="xxx_xxxx";
        obj.workPlace="Egypt";
        obj.Salary=1000000;

        obj.printDetails();
        Employee obj1=new Employee();
        obj1.age=29;
        obj1.name="asser";
        obj1.pension=100_000;
        obj1.teleNo="xxx_xxxx";
        obj1.workPlace="rgypt";
        obj1.Salary=2000000;
        obj1.printDetails();
    }
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • you can easily find more info by googling: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – Subler Mar 09 '15 at 15:05
  • `this` always refers to current instance of a class. So you need not use unless there's a method local variable having with same name but you want to make use of your instance variable, then we explicitly prefix our variable name with `this` to tell the compiler that we need to use instance variable instead of a local variable in that case – Arkantos Mar 09 '15 at 15:06

4 Answers4

10

It's always optional unless you are referencing a field which has the same name as a local variable. For example:

class Sample
{
    int value;

    void method(int value)
    {
        this.value = value; //this is required
    }
}

If this is not the case, then using this behaves identically to referencing the variable directly.

Kon
  • 10,702
  • 6
  • 41
  • 58
4

this in Java is optional, unless you have a local variable or parameter of the same name, in which case the variable name will be referring to the latter.

public class Employee {

    private String name = "one";

    public void printDetails() {
        String name = "two";
        System.out.println(this.name); // "one"
        System.out.println(name); // "two"
    }
}
Jaroslaw Pawlak
  • 5,538
  • 7
  • 30
  • 57
1

You need to use 'this' when you have variables in different 'scopes' which have the same name. So if you have an instance variable and a variable in a method which are called the same thing, you must prefix the instance variable with 'this', otherwise the local variable will override the instance variable.

Otherwise it is optional and is a matter of personal preference.

Some people like the scope of a variable to be explicit in the code - others think this is clutter and unnecessary.

Personally, I would aim to not have the same names for variables in different scopes if possible.

Dan Saunders
  • 280
  • 2
  • 10
1

this is always optional with the exception of referring to a field which is named the same both locally and globally. e.g:

class test
{
    int varname; //global 

    public void testMethod(int varname)
    {
        this.varname=varname; //this.varname refers to the declaration within the class, not the method (the global 'varname' variable)

    }

As others has mentioned, it's always worth reading the documentation.

Also, this refers to the current object. As per the documentation, this means that this refers to the current object whose method or constructor is being called. So, for example, if you had some code that declared a Swing component and attached an action listener to it, code within that action listener would refer to the action listener if prefixed with the this keyword:

swingJButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        this.actionPerformed(e); // <-- refers to "new ActionListener()" object above
    } });

For simplicity, it's best to just avoid using the keyword unless you have to. Some programmers prefer using the same variable names within different scopes - its rather common in so called setter methods, others do not - that's down to preference; whichever you choose, be aware of that this is referring to.

PsychoMantis
  • 993
  • 2
  • 13
  • 29