I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instanc
I am wondering when to use static methods?
static
methods is to access static
fields. But you can have static
methods, without referencing static
variables. Helper methods without referring static
variable can be found in some java classes like java.lang.Math
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
The other use case, I can think of these methods combined with synchronized
method is implementation of class level locking in multi threaded environment.
Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
If you need to access method on an instance object of the class, your method should should be non static.
Oracle documentation page provides more details.
Not all combinations of instance and class variables and methods are allowed: