static members of a class are fields and methods that have the keyword static as a modifier preceding the type of field or method. Local variables (variables declared within methods) may not be declared static. Constructors may not be declared static.
static indicates that only one copy of the field variable exists.Fields that should be declared
static
// declare static fields inside the class and outside methods
// class (static) fields must be assigned initial values when declared
public static final char[] DIR = { 'N', 'E', 'S', 'W' };
private static int numberOfInstancesCreated = 0;
private static double timeStepsSinceStartOfProgram = 0;
static modifier indicates that each instance (object) of that class (type) will have its own copy of the field.Fields that should NOT be declared
static
// declare fields inside the class and outside methods
// instance fields will be assigned values in the constructor
public final int SERIAL_NUMBER;
private int score;
private String name;
static is done if the method only needs to access or set static fields of the class.// declare static methods inside the class and outside other methods
// static methods may only access (use) static fields
public static int getNumberOfInstances() {
return numberOfInstancesCreated;
}
private static boolean isValidDirection( char d ) {
boolean valid = false;
for ( int i=0; i < DIR.length; i++ ) {
if ( d == DIR[i] ) valid = true;
}
return valid;
}
private static double getTimeSteps() {
return timeStepsSinceStartOfProgram;
}
static modifier indicates that this method will need to access or set instance (non-static) fields of the class.// declare non static methods inside the class and outside other methods
// instance (non static) methods may access (use) any fields
public long getMySerialNumber() {
return SERIAL_NUMBER;
}
private int getScore() {
return score;
}
private String changeName( String newName ) {
name = newName;
}
private String getName() {
return name;
}