3.7 - Class Variables and Methods
Class methods (the
static ones) can’t access or change instance variables, or call instance methods, unless they’re actually given an instance of the class as a parameter to work with.Class methods can access and change class variables, and they can call other class methods freely.
Class variables belong to the class itself, not to any individual object, so every object of that class shares the exact same single copy. You mark them with the
static keyword.public class Dog { public static int totalDogs = 0; // class variable, shared by every Dog object public Dog() { totalDogs++; // every new dog increases the shared count } }
If a class variable is
public, you access it from outside using the class name and the dot operator, since it belongs to the class, not to any specific object.System.out.println(Dog.totalDogs); // accessed through the class name
Here’s a class that puts class variables and class methods together. Constructors and instance methods can use class variables too, which is how the constructor keeps
totalDogs up to date:public class Dog { private String name; public static int totalDogs = 0; public Dog(String n) { name = n; totalDogs++; } public static int getTotalDogs() { return totalDogs; // allowed: a class method can use a class variable } public static boolean hasName(Dog d, String n) { return d.name.equals(n); // allowed: a Dog object was passed in as a parameter } public void bark() { System.out.println(name + " says woof"); } }
Dog a = new Dog("Rex"); Dog b = new Dog("Bella"); System.out.println(Dog.getTotalDogs()); // 2 System.out.println(Dog.totalDogs); // 2, the same shared value System.out.println(Dog.hasName(a, "Rex")); // true
What a class method can’t do is use an instance variable or call an instance method on its own, because there’s no object to get them from. Adding either of these to the
Dog class above causes a compile error:public static String getName() { return name; // compile error: there's no object here, so there's no name to return } public static void makeNoise() { bark(); // compile error: bark() needs a Dog object to be called on }
If a variable is declared
final, its value can never be changed after it’s set.static final double PI_APPROX = 3.14159; // can't be reassigned later
Trying to change a
final variable is a compile error. Constants are usually named in all capital letters, and final works for local variables too:final int MAX_LEVEL = 10; MAX_LEVEL = 12; // compile error: MAX_LEVEL is final, so it can't be reassigned