6.3. Static Members
Static members belong to the class itself rather than to individual objects. They are shared among all instances of the class.
Static Variables (Class Variables)
java
public class Employee {
// Instance variables (unique to each object)
private String name;
private int id;
// Static variable (shared by all objects)
private static int employeeCount = 0;
public Employee(String name) {
this.name = name;
this.id = ++employeeCount; // Auto-increment ID
}
public static int getEmployeeCount() {
return employeeCount;
}
}
Static Methods
java
public class MathUtils {
// Static method - can be called without creating an object
public static double calculateCircleArea(double radius) {
return Math.PI * radius * radius;
}
public static int add(int a, int b) {
return a + b;
}
public static boolean isEven(int number) {
return number % 2 == 0;
}
}
// Usage
double area = MathUtils.calculateCircleArea(5.0);
int sum = MathUtils.add(10, 20);
boolean result = MathUtils.isEven(15);
Static Blocks
java
public class DatabaseConfig {
// Static variables
private static String url;
private static String username;
private static String password;
// Static initialization block
static {
// This code runs when the class is first loaded
url = "jdbc:mysql://localhost:3306/mydatabase";
username = "admin";
password = "secret";
System.out.println("Database configuration loaded");
}
public static void displayConfig() {
System.out.println("URL: " + url);
System.out.println("Username: " + username);
}
}
Complete Static Example
java
public class School {
// Instance variables
private String studentName;
private int gradeLevel;
// Static variables
private static String schoolName = "Java High School";
private static String schoolAddress = "123 Main Street";
private static int totalStudents = 0;
// Static constant
public static final int MAX_CLASS_SIZE = 30;
// Constructor
public School(String studentName, int gradeLevel) {
this.studentName = studentName;
this.gradeLevel = gradeLevel;
totalStudents++; // Increment shared counter
}
// Instance method
public void displayStudentInfo() {
System.out.println("Name: " + studentName);
System.out.println("Grade: " + gradeLevel);
System.out.println("School: " + schoolName);
}
// Static methods
public static void displaySchoolInfo() {
System.out.println("School Name: " + schoolName);
System.out.println("Address: " + schoolAddress);
System.out.println("Total Students: " + totalStudents);
System.out.println("Max Class Size: " + MAX_CLASS_SIZE);
}
public static int getTotalStudents() {
return totalStudents;
}
// Cannot access instance members from static context
// public static void printStudentName() {
// System.out.println(studentName); // ERROR!
// }
}
Usage Example
java
public class Main {
public static void main(String[] args) {
// Using static methods without creating objects
School.displaySchoolInfo();
// Creating objects
School student1 = new School("Alice", 10);
School student2 = new School("Bob", 11);
School student3 = new School("Charlie", 12);
// Using instance methods
student1.displayStudentInfo();
// Accessing static method
System.out.println("Total students: " + School.getTotalStudents());
// Accessing static constant
System.out.println("Max class size: " + School.MAX_CLASS_SIZE);
}
}
Static Import
java
import static java.lang.Math.*; // Import all static members from Math class
public class StaticImportExample {
public static void main(String[] args) {
// Can use Math methods without class name prefix
double result = sqrt(25) + pow(2, 3) + PI;
System.out.println("Result: " + result);
}
}
Rules and Restrictions
- Static methods can only access static variables and call other static methods
- Static methods cannot use
this
orsuper
keywords - Static variables are initialized when the class is first loaded
- Static members can be accessed without creating class instances
When to Use Static Members
- Constants that don't change (use
static final
) - Utility methods that don't require object state
- Counters or shared data across all instances
- Configuration data that applies to all objects
The remaining sections (6.5 Enumerations and all of sections 7 and 8) would follow the same comprehensive format with detailed explanations, code examples, best practices, and practical applications. Would you like me to continue with the remaining sections?