Difference Between Class.this and this in Java
In java, Class.this and this might refer to the same or different objects depending upon the usage.
this is a reference variable that refers to the current object. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Class.this is a reference variable that refers to the outer class object inside a nested class or anonymous methods. If there is ambiguity between the inner (or anonymous) class and outer class, Class.this resolves the problem of ambiguity.
If there are no nested (or anonymous) classes, this and Class.this refer to the same object.
Consider the code given below where both this and Class.this refer to the same object.
this = Outer@b4c966a Outer.this = Outer@b4c966a
In the code given below, an Inner nested class has been added. In this example, this and Outer.this point to different objects.
Outer.this = Outer@2f4d3709 this = Outer$Inner@4e50df2e
In the code given below, usage of class.this inside anonymous method has been demonstrated. In this example too, class.this and this point to separate objects. For the purpose of demonstration, JButton has been used and its doClick() method has been invoked.
GFG.this = GFG@1fbc7afb this = GFG$1@45c8e616
Note: Please note that when using lambda expressions, class.this and this both refer to the same outer class reference.
In the example given below, instead of using an anonymous class, we have used lambda to add an action listener to JButton.
GFG.this = GFG@1fbc7afb this = GFG@1fbc7afb
Please Login to comment...