Static Methods
1. What Static Means (beginner)
Static = belongs to class, not object. Call without new: Math.sqrt(16). Shared single copy (no this!). Utility functions live here!
2. Code — Counter Proof (static vs instance!)
class Demo {
static int count = 0; // ONE copy (shared!)
int id; // per-object copy!
Demo() { count++; id = count; }
static int total() { return count; } // static (no object needed!)
int getId() { return id; } // instance (needs object!)
}
Demo a = new Demo(); Demo b = new Demo();
System.out.println(Demo.total()); // 2 (class call!)
System.out.println(a.getId() + " " + b.getId()); // 1 2 (separate!)
// System.out.println(Demo.getId()); // ERROR! (needs object!)
3. Rules (exam traps!)
- Static method: NO
this, NO instance vars (no object to read from!). Can use static vars + params only. - Static method CAN be called via object (
a.total()compiles) but style police: useDemo.total(). mainis static (JVM calls withoutnew!).
4. When Static?
Pure helpers (add, sqrt), factories, counters. Need object state? Instance!
5. Exam Points
- Static vs instance + counter program — 5-7 marks, very frequent.
thisban in static — 3 marks, favourite error.