i would like to ask the question when it would be advantageous to use static variables/methods or in the other case instance variables/methods in Java?
I know that it depends on the certain case (like programming util-classes as static methods), but can we declare something like a general strategy?
At novice level :
Use instance variables when : Every variable has a different value for different object. E.g. name of student, roll number etc..
use static variables when : The value of the variable is independent of the objects (not unique for each object). E.g. number of students.
static
variables are often used for constants, which is common to all the instances if the class. For example, many people don't like to "hard-code" constants in their code; they like to make apublic static
orprivate static
variable with a meaningful name and use that in their code, which should make the code more readable.In Short
Any method or variable that is independent of the state of an instance of the class should be static.
Static variable: When you need something that will be used through out the application and every instance need to know the variable.
Instance variable: It will be different from object to object and object's property while static variable is Class's property.
Static function: Used to do some utility task. Can be called without any object declaration.
Instance function: Need object to call this function.
static or instance depends on your uses .
Think of static variables as class-wide global variables or, if you use "final" keyword, as class-wide global constants. Use static non-final variables wisely - they are shared among all class instances and it may lead to some non-obvious mistakes. I would recomend avoid using mutable static variables at all - there are small to none cases, where such need couldn't be implemented using dependency injection.
Also using globals always makes unit-testing lot harder - one more drawback to consider.
As for methods : every method
Foo.method(Bar1 b1, Bar2, b2)
by definition could always have alternative equivalent designs:Bar.altmethod(Foo f, Bar b2)
and
static staticMethod(Foo f, Bar b1, Bar b2)
And you could also wrap that latter method as an instance method in a service class which is itself a singleton (so that the static-ness of the method is a bit little bit concealed by the class it's in).
The only compelling reason to have your method as an instance method of the class of one of your method arguments (of the static version), is when you expect there to be subclasses for that class, and that it might be useful for those subclasses to have a specialized implementation of the method.
Imagine
It might be useful to leave open the possibility of later adding
Other than that, all your options are essentially equivalent.