Objects and Classes
Static fields and methods
Code
How to code static fields and methods
- You can use the static keyword to code static fields and static methods.
- Since static fields and static methods belong to the class, not to an object created from the class, they are sometimes called class fields and class methods.
- When you code a static method, you can only use static fields and fields that are defined in the method.
- You can't use instance variables in a static method because they belong to an instance of the class, not to the class as a whole.
How to declare static fields
private static int numberOfObjects = 0; private static double majorityPercent = .51; public static final int DAYS_IN_JANUARY = 31; public static final float EARTH_MASS_IN_KG = 5.972e24F
A class that contains a static constant and a static method
public class FinancialCalculations { public static final int MONTHS_IN_YEAR = 12; public static double calculateFutureValue( double monthlyPayment, double yearlyInterestRate, int years) { int months = years * MONTHS_IN_YEAR; double monthlyInterestRate = yearlyInterestRate/MONTHS_IN_YEAR/100; double futureValue = 0; for (int i = 1; i <= months; i++) futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); return futureValue; } }
The Product class with a static variable and a static method
public class Product { private String code; private String description; private double price; private static int objectCount = 0; // declare a static variable public Product() { code = ""; description = ""; price = 0; objectCount++; // update the static variable } public static int getObjectCount() // get the static variable { return objectCount; } ...