Static code
At this point it is worth stopping to take a more detailed look at another important concept: the static keyword. You have seen one example so far of a static method: the main method of the program. The static keyword can in fact be used on any field or method.
The static modifier means that the method or field exists on the class itself, rather than instances of the class. If a field is static, therefore, it only ever has a single value, no matter how many instances of the class are created.
To see this in action, add a new field to the Car class as follows:
public static int staticField = 1;
Now add the following code to the main method of Main:
car2.staticField = 5;
System.out.println("The static field on car 1 is "+car1.staticField);
System.out.println("The static field on car 2 is "+car2.staticField);
car1.staticField = 10;
System.out.println("The static field on car 1 is "+car1.staticField);
System.out.println("The static field on car 2 is "+car2.staticField);
This will produce the following output:
The static field on car 1 is 5
The static field on car 2 is 5
The static field on car 1 is 10
The static field on car 2 is 10
As can be seen, modifying a static field on one object affects the field’s value on all of the objects – this is because staticField is an attribute of the class itself.
A more correct way to modify this field is without even referencing an object. To see this approach, place the following code at the very beginning of the main method (before any objects are created):
Car.staticField = 20;
System.out.println("The static field is "+Car.staticField);
Methods can also be static. For instance, you could add the following method to Car:
public static void addToStaticField(int number) {
staticField = staticField + number;
}
This method accepts a number as a parameter, and then adds that number to the current value of staticField. This can be used as follows in the main method:
Car.addToStaticField(10);
It is very important to understand, however, that although a static method can access or modify a static field, it cannot access a non-static field (or other non-static methods). This is because non-static fields only exist on objects, whereas a static method can exist independent of objects.
static methods and fields do have their place, but as you will see in the chapters to come, it is generally best to avoid them where possible because they break important object orientated principles that we will discuss shortly.
If you come from an imperative programming background you may be tempted to write Java programs entirely with static methods, because this allows you to ignore the object-orientated nature of Java. This is a mistake, and hopefully you will be convinced of this by the end of the book.