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:
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:
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:
3. Create 'AccessStaticMethod' class as shown below:
6. Observe that the output is displayed in console as shown below:
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:
Post a Comment