Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is the difference between this.method() and method()?

Tags:

java

methods

Is there any difference between calling this.method() and method() (including performance difference)?

like image 458
nebkat Avatar asked Jul 01 '11 11:07

nebkat


People also ask

What is the difference between this and this () in Java?

In Java, both this and this() are completely different from each other. this keyword is used to refer to the current object, i.e. through which the method is called. this() is used to call one constructor from the other of the same class.

What is this () method in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

What is the main () method in Java?

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs .

Can we use this () in a method?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it.


2 Answers

The only time it matters is if you are using OuterClass.this.method() e.g.

class OuterClass {     void method() { }      class InnerClass {         void method() {             OuterClass.this.method(); // not the same as method().         }     }  } 
like image 141
Peter Lawrey Avatar answered Oct 01 '22 02:10

Peter Lawrey


There is absolutely no difference between these constructs and the generated bytecode will be exactly the same, hence no performance impact. this is resolved during compilation if not explicitly defined.

The only reason for using explicit this is readability - some people find it easier to read because this suggests that this is an instance method of current object.

Also please note that if method() is static, using this is discouraged and misleading.

private static void method() { }  private void foo() {     this.method();    //generates warning in my IDE for a reason } 

And in this case it will also have no effect on performance.

like image 22
Tomasz Nurkiewicz Avatar answered Oct 01 '22 02:10

Tomasz Nurkiewicz