Static Members
Static Members
Section titled “Static Members”Introduction
Section titled “Introduction”Static members (also called class-level members) belong to the class itself, not to individual instances. They are shared across all instances and can be accessed without creating an object.
Real-World Analogy: School
Section titled “Real-World Analogy: School”| Concept | Analogy |
|---|---|
| Instance members | Each student’s name, grades, locker number |
| Static members | School name, total enrollment, bell schedule |
| Static method | Calculate GPA formula (same for all students) |
Code Examples
Section titled “Code Examples”class Configuration { static appName = "MyApp"; static version = "1.0.0"; static #apiKey = "secret-key-123"; // Private static!
static getAppInfo() { return `${Configuration.appName} v${Configuration.version}`; }}
console.log(Configuration.appName); // "MyApp"class Circle: pi = 3.14159 circle_count = 0
def __init__(self, radius): self.radius = radius Circle.circle_count += 1
@classmethod def from_diameter(cls, diameter): return cls(diameter / 2)
@staticmethod def calculate_area(radius): return Circle.pi * radius ** 2Static vs Instance Members
Section titled “Static vs Instance Members”| Aspect | Static Members | Instance Members |
|---|---|---|
| Belongs to | The class | The instance |
| Access | ClassName.member | object.member |
| Memory | One copy shared | Copy per instance |
| Can access instance data? | No | Yes |
When to Use Static
Section titled “When to Use Static”✅ Good Uses
Section titled “✅ Good Uses”- Constants (
MAX_SIZE,PI) - Factory methods (
Promise.resolve()) - Utility functions (
Math.round()) - Counters (track number of instances)
❌ Bad Uses
Section titled “❌ Bad Uses”- Overuse of static methods (procedural code in OOP clothing)
- Global mutable state
Previous Topic: Access Modifiers → Next Topic: Interfaces →