When to use static variables/methods and when to use instance variables/methods in Java?
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 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 .
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 a public static
or private 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.