Google+

86. 'static' methods






As we've already discussed that we can access 'static' methods without creating any objects outside the class by calling the 'static' method using ClassName.methodName( ) statement.

Lets implement this on Eclipse IDE:

1. Create a class 'StaticMethodDemo' under 'twelve_package' package of 'Twelve Project' project as shown below:



2. Create sample( ) method and specify it as 'static' ( also specify it as 'public' in order to access it from any class that is in a different package:) as shown below and save:



3. Create another class named 'AccessStaticMethods' under the same package 'twelve_package' as shown below:



4. Call the 'static' method in 'StaticMethodDemo' class as shown below:


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



At this point, we have to understand that we can access 'static' method of other class without creating any object. We have to find out whether we can access the 'static' methods from a class under a different package by following the next steps.

7. Create 'DifferentPackageAccess' class under 'different_package' as shown below:



8. Call the 'static' method in 'StaticMethodDemo' class as shown below:



9. Save and Run the 'DifferentPackageAccess' class
10. Observe that the output is displayed in console as shown below:



At this point we've to understand that we can access 'static' method without creating an object from a class of different package. We didn't get any access error, as we have specified 'static' method as 'public' in 'StaticMethodDemo' class.

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 can only call 'static' methods will be explained with an example in next post.




No comments: