Static Variables and Methods
You access them by writing classname.variable or classname.method()
Example:
double d = Math.random();
You are using the static method random() from the Math class.
double radians = degrees * Math.PI / 180.0;
PI is a static variable in the Math class.
Note that you never have to create a Math object in order to access these fields. (e.g. never Math mmm = new Math(); mmm.random();
)
- To run a program you must have
public static void main() {}
- Static things exist at the class level. There is only one copy of these.
If you change a static variable, it changes for all objects of that class. - Static varibles and methods are made automatically when the program compiles.
- Static functions cannot access anything that is not static. This is because instance variables and instance methods exist in individual objects not in the class. There may be many multiple different copies of these if you have created many objects, and each can have its own value. So it makes no sense to have a static method try to access an instance variable. Which of the many objects should it look at?