Aqua Phoenix
     >>  Lectures >>  Java 2  
 

Navigator
   
 
       
   

2.5 static

UNDER CONSTRUCTION: THIS SECTION IS NOT YET COMPLETE

Example:

class TheMessage {
int x;

public static void main(String[] args) {
  x = 10;
}
}
Compile Error: non-static variable x cannot be referenced from a static context!

Static: class variables/methods

Non-static: instance (object) variables/methods

Static variables and methods are associated with the class!

Instance variables/methods are associated with a particular instantiated object

Static - Can be called directly using the class name!

For example:

result = Math.sqrt(25);  //static method
piValue = Math.PI;  //static variable
Only one copy of the variable exists for the entire class

private static float price;
Memory space for a static variable is created when the class is first referenced

All objects instantiated from the class share its static variables

Changing the value of a static variable in one object changes it for all others!!!

cannot reference instance variables (because instance variables don't exist until an object exists)

can reference static class variables or its own local variables

main() is static – it gets invoked before any class is instantiated

Example:

Let’s make our Person class know how many Person objects were instantiated