Non-static vs. Static Variables

Whether or not an instance variable is static refers to whether or not each instance of a class has its own version of the variable, or if, instead, all instances of a class share the same variable. Despite the name, static variables can be changed (variables that can not be changed are called final). Static only refers to the scope of the variable.

Non-static Variables

Non-static variables are variables where every instance of the class has its own version of that variable. The values of these variables can vary between instances of the same class. We want each Dot to have a potentially unique position, so our x- and y-coordinates must not be static.

Static Variables

Static variables, on the other hand, are shared among all instances of the same class. In this example, we want every Dot to have the same radius and the same color, so we want these variables to be static.

Should I Use a Static or Non-static Variable?

We could have made the color and radius variables non-static. However, this would mean that every instance of the Dot class will have its own variables to represent the color and the radius. Since we want all of these variables to be the same, and because there will never be a situation where one of the Dots will have a different color or radius, it would be a waste of memory to have that many copies of the same information. With a static variable, the one shared variable is the only copy that exists. In addition, if you wanted to change the color of all the Dots, with a non-static variable, you would need to access each instance of the Dot class and then change its color. With static variables for the color, you only need to change the color once, and then the color of all the dots will change.

Be sure that you only use static variables when you want the variable to be unable to change independently for each instance, not when variables are coincidentally the same.