Static Fields
A static field belongs to the class, not to any object of the class. Also called class field
public class BankAccount
{
. . .
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 1000;
}
If
lastAssignedNumber
was not
static,
each instance of
BankAccount
would have its own value of
lastAssignedNumber
public BankAccount()
{
// Generates next account number to be assigned
lastAssignedNumber++; // Updates the static field
// Assigns field to account number of this bank account
accountNumber = lastAssignedNumber; // Sets the instance field
}
Minimize the use of static fields (static final fields are ok)
Three ways to initialize:
Do nothing. Field is initialized with 0 (for numbers), false (for boolean values), or null (for objects)
Use an explicit initializer, such as
public class BankAccount
{
. . .
private static int lastAssignedNumber = 1000;
// Executed once,
// when class is loaded
}
- Use a static initialization block
public class BankAccount
{
. . .
private double balance;
private int accountNumber;
private static int lastAssignedNumber;
static
{
lastAssignedNumber =1000;
}
}
Static fields should always be declared as private
Exception: Static constants, which may be either private or public
public class BankAccount
{
. . .
public static final double OVERDRAFT_FEE = 5; //
Refer to it as
// BankAccount.OVERDRAFT_FEE
}
Name two static fields of the System class.
Answer: System.in and System.out.