Is there any difference between calling this.method()
and method()
(including performance difference)?
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.
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).
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 .
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.
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(). } } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With