Google+

87. 'static' methods can only call 'static' methods



Lets find out what happens when a 'static' method calls a method which is not declared as static.

Lets implement this on Eclipse IDE:

1. Create 'StaticMethodCalling' class under any project as shown below:



2. Create 'sample( )' method and don't specify it as 'static' as shown below:



3. Create 'static' specified 'staticSample( )' method and call 'sample( )' method which is not specified as 'static' as shown below and save:


4. Observe that the 'sample( )' method calling statement inside the 'staticSample( )' method is giving an error. Click on the 'sample( );' statement to find out the error details. Observe that the following error details are displayed as shown below:



After looking at the error "Cannot make a static reference to the non-static method sample( )" , its very clear that 'static' methods cannot call non-static methods.

Download this Project:

Click here to download the 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 a 'static' method calls other 'static' method

Lets implement this on Eclipse IDE:

1. In the above project, open the 'StaticMethodsCalling' class and specify 'static' before the non-static method 'sample( )' as shown below and save:



2. Observe that the error displayed in the step 4 of above project is now fixed as shown below:



At this point, we have to understand that 'static' methods can call only the 'static' methods. Lets run this program by creating another class and accessing the static method 'staticSample( )' from it.

3. Create another class 'AccessStaticMethods' with main( ) method as shown below:



4. Call the 'static' method 'staticSample( )' of 'StaticMethodCalls' class without creating any object from  'AccessStaticMethods' class (i.e. Use Class Name to access it as it is a static method) as shown below:



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



What happened ?

We've called the 'staticSample( )' static method from 'AccessStaticMethods' class without creating object and  'sample( );' calling statement inside the 'staticSample( )' called the 'static' specified method 'sample( )' and executed the print statement inside the 'sample( )' method.

Download this project:

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




Please comment below to feedback or ask questions.

'static' methods can only access 'static' instance variables will be explained with an example in next post.




No comments: