Running Race - Explaining Static


Trying to understand static can be difficult ….

You use static when you don’t want to use an instance, or you don’t have an instance of the class (so you haven't made a "new" object or instance). For example, the main method is always static because when the program starts, no instances have been created.

Static variables belong to the class, which means that all instances of the class share the same value of the variable.

Here is an example:


Task: Create a class for athlete/marathon runners in a single race.

     Requirements:
          Give out sequential bib-numbers (start at 1)
          Set the race location & start time


Copy the code below, then modify it so that each athlete gets a unique, sequential bib number.


public class Athlete {

     static int nextBibNumber;
     static String raceLocation = "New York";
     static String raceStartTime = "9.00am";

     String name;
     int speed;
     int bibNumber;

Athlete (String name, int speed){
     this.name = name;
     this.speed = speed;
}

public static void main(String[] args) {
     //create two athletes      //print their names, bibNumbers, and the location of their race. }
}


So the static variables belong to the class and the other variables belong to the instance.

What happens to the variables when the 2 constructors run? How does nextBibNumber change, and when is the bib number assigned?

How can you change the location of the race? Is it updated for all the athletes?