Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
wy we use static in java and what is the purpose of static in java
Posted

The purpose if very different for fields, properties and methods. For fields and properties, static objects are the class objects; there is only one instance of such member for the class; if the class is not instantiated at all, there is one instance of such member; if you instantiate several instanced of the class, this is still one instance of this member.

Static methods are just the methods which don't have that "this" referenced which is passed as an implicit argument when one calls an instance method. So, naturally, static methods don't have access to any instance members, but only to other static members for the class.

Now, the use of it… Actually, static methods are very important. If you have all input only in arguments, and output is void or all is put in return value, you should always use a static method. The access to the instance is not needed, would be superfluous and even more error-prone. For those familiar with non-OOP languages: this is pretty much like old-day non-OOP function. No access to objects, no objects.

You can also access any other static members, first of all, other static methods. You can also access static fields and properties, but is it good? The thing is: static fields and properties themselves should be used with care. One can avoid them totally; and excessive use of them can be considered as a sign of bad programming style. You can always use instance members and create an instance, if required, only one instance. That said, it has something to do with the singleton pattern, which itself should be used with care, minimally. So, the singleton can be implemented using static members. Please see: http://en.wikipedia.org/wiki/Singleton_pattern.

For Java implementations, please see:
http://www.javaexperience.com/design-patterns-singleton-design-pattern,
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html.

Syntactically, all static members are accessed via the name of the class, not via the name of any variable/member referencing instance of the class.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900