Class fields
Variables declared in a class and not in a method call are referred to as fields. They fall into two categories:
- Instance variables
- Class variables
Instance variables are unique to every instance of the class. They can be primitives or references. If we had an instance variable of type double
in a class and we created 100 instances of the object, we would have 100 doubles.
In Java, you can have a variable in a class that is shared by all objects created from the class. In other words, every object has a unique set of instance variables, but all share the class variables. This is accomplished by designating the variable as static. There is only one memory allocation for a static variable. In our 100 instances of an object, there is just one double if you declare the double as static.
Another characteristic of a static or class variable is that assuming it has public access control, you can access it without instantiating the object. For example...