Calling Instance Method with 'this' vs. calling it without 'this' - is there a difference?

317 Views Asked by At

Is there any difference between the call to getName() on line 8 and that on line 9.

If yes, then what is it?

This might be very simple but I did my Google search and the only SO result I got was about using this with a field, and not with a method.

class CallingInstanceMethodWithAndWithoutThis {

    private String getName() {
        return "Zarah";
    }

    private void printGetName() {
        System.out.println(getName());
        System.out.println(this.getName());
    }

    public static void main(String [] args) {
        new CallingInstanceMethodWithAndWithoutThis().printGetName();
    }

}
3

There are 3 best solutions below

0
On BEST ANSWER

There is no difference, it is just a coding convention to use. Moreover you can ask Eclipse for instance to remove automatically "this" when not needed as a Save Action.

0
On

For the compiler there is no difference, but it may cause collisions in some cases. Generally not using this will be OK, java compiler is smart enough to recognize our intentions, but it is strongly recommended to use this keyword anyway (e.g. in setters), IMO it's more clear to understand where the method comes from (in case your class extends other or you import some methods statically).

0
On

There is no difference between using this and not using it.

To check this, in fact, if we perform disassemble using javap -p -c CallingInstanceMethodWithAndWithoutThis the output is below :

  private void printGetName();
    Code:
       0: getstatic     #19                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: aload_0
       4: invokespecial #25                 // Method getName:()Ljava/lang/String;
       7: invokevirtual #27                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      10: getstatic     #19                 // Field java/lang/System.out:Ljava/io/PrintStream;
      13: aload_0
      14: invokespecial #25                 // Method getName:()Ljava/lang/String;
      17: invokevirtual #27                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V

We can notice that the output at line 0 and line 10 (where we are calling getName() method) are same and there is no difference.