Careeroza
Static vs Instance Members
One Copy vs One Per Object
Instance fields belong to each object: every Student has its own name. Static fields belong to the class: there is exactly one copy shared by all objects.
| Instance member | Static member | |
|---|---|---|
| Belongs to | each object | the class |
| Copies | one per object | one in total |
| Accessed with | obj.field | ClassName.field |
Can use this | yes | no (there is no current object) |
| Typical use | object data (name, balance) | counters, constants, utility methods |
Counting Objects with a Static Field
Example
public class Main {
public static void main(String[] args) {
new User("Asha");
new User("Ravi");
User u = new User("Meena");
System.out.println("Last user id: " + u.id);
System.out.println("Total users: " + User.count);
}
}
class User {
static int count = 0; // shared by all users
int id; // each user has its own
String name;
User(String name) {
count++;
this.id = count;
this.name = name;
System.out.println("Created " + name + " with id " + id);
}
}Output
Created Asha with id 1 Created Ravi with id 2 Created Meena with id 3 Last user id: 3 Total users: 3
Static Methods and Static Blocks
A static method can be called without an object, like Math.max(). It can only use static fields directly. A static block runs once, when the class is first loaded, and is used to set up static data.
Example
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
System.out.println("GST on 1000: " + Tax.gst(1000));
System.out.println("GST on 500: " + Tax.gst(500));
}
}
class Tax {
static final double RATE;
static {
System.out.println("Tax class loaded");
RATE = 0.18;
}
static double gst(double amount) {
return amount * RATE;
}
}Output
Main started Tax class loaded GST on 1000: 180.0 GST on 500: 90.0
Note: Notice "Tax class loaded" prints only once, and only when Tax is used for the first time.
Common Mistake
A static method cannot touch instance fields, because there is no object to read them from.
class Counter {
int value;
static void reset() {
value = 0; // compile error: non-static variable value cannot be referenced from a static context
}
}Tip: Rule of thumb: if a method does not use any instance field, it can be static (for example, helper methods in a Utils class).