89. 'static' methods cannot refer to 'this' keyword

'Static' methods cannot use 'this' keyword.

Lets try to use 'this' keyword in 'static' methods by implementing this on Eclipse IDE:

 1. Create 'ThisDemo' class under a project as shown below:

2. Create 'static' specified instance variables 'width', 'height' and 'depth' as shown below:

3. Create 'static' specified method 'setDimensions( )' containing the parameters same as instance variable of this class (i.e. width,  height and depth) and this 'static' specified method tries to use 'this' to differentiate the instance variables from the parameters of this method as shown below:

Observe that errors are displayed in the statements that are using 'this' keyword

4. Hover the mouse over the 'this' keyword in any of the above statements as shown below:

After looking at this error 'Cannot use this in static context', its very clear that we cannot use 'this' keyword in a static method.

Download this project:

Click here to download this project containing class files used in this post (You can download this project and import into Eclipse IDE on your machine)

Please comment below to feedback or ask questions.

'static' block will be explained with an example in next post.


Vijaykumar Mohith said...

What is the reason behind it ?

Moni Mathur said...

this is used to refer to the parent object of a variable or method. When you declare static on a method the method can be called without needing to instantiate an object of the class. Therefore the this keyword is not allowed because your static method is not associated with any objects.

Followers :)

Blog Index