About
Object - Static in Java.
Articles Related
Type
Method
The Java programming language supports static methods.
Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)
You can also refer to static methods with an object reference like
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.
A common use for static methods is to access static fields.
The Java platform lets you execute a class without creating an instance of that class as long as its static methods do not call any non-static methods or fields.
You can call any static method from anywhere. That's why they are best suited for:
- factory method (in order to create instances)
- or utility method.
java.lang.Math class is a perfect example where almost all methods are static.
Variable
The Java programming language supports static variables.
The static modifier in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
Member
You specify a class variable by using the static keyword in the member's declaration.
Without Static
A member that is not declared as static is implicitly an instance member.
(Non-Static Fields) Instance Variable. Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance (variables|member) because their values are unique to each instance of a class.
For example: the currentSpeed of one bicycle is independent from the currentSpeed of another.
Static
Class Variable (Static Fields) A class variable is any field declared with the static modifier.
Thread-Safe
Shared resources are not thread-safe. Hence Static method or variables are not thread safe. Constants using static and final keyword are read-only and therefore are thread safe.
If you want thread safety, you have to synchronize the static method. When a static synchronized method is invoked (a static method is associated with a class, not an object), the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.