Google+

88. 'static' methods can only access 'static' varaibles







Lets find out what happens when a 'static' method accesses an instance variable which is not declared as 'static'

Lets implement this on Eclipse IDE:

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



2. Create an instance variable which is not of 'static' type



3. Create 'static' specified 'staticSample( )' method which prints the instance variable which is not of 'static' type as shown below and save:

4. Observe that an error is displayed with the instance variable 'a' and to find out, hover the mouse over the instance variable 'a' as shown below:



After looking at this error 'Cannot make static reference to the non static field a ', its very clear that  instance variables of non static type cant be used by  'static' methods.

Download this project:

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

Lets find out what happens when 'static' instance variable is accessed by 'static' method.

Lets implement this on Eclipse IDE:

1. In the above project, open 'StaticMethod' class and specify 'static' before the non-static instance variable 'a' as shown below and save:



2. Observe that the error displayed in the step 4 of above project got resolved as shown below:





At this point you have to understand that, 'static' methods can only use 'static' instance variables. Lets run this program by creating another class and accessing the 'static' specified 'staticSample( )' method.

3. Create 'AccessStaticMethod' class as shown below:





4. Call the static specified 'staticSample( )' method of 'StaticMethod' class without creating any object to access it as shown below:





5. Save and Run the 'AccessStaticMethod' class
6. Observe that the output is displayed in console as shown below:





What just happened? 

We've called the 'static' specified 'staticSample( )' method of 'StaticMethod' class without creating any object.  'staticSample( )' method has executed the statement which prints the 'static' specified instance variable 'a'.

Download this project:

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





Please comment below to feedback or ask questions.

'static' methods cannot refer to 'this' keyword will be explained with an example in next post.




No comments:

Blog Index