Static vs Instance Members
By the end of this lesson, you'll be able to:
- Distinguish a static field/method from an instance field/method
- Explain that static members belong to the class itself, not to any one object
- Call a static method without creating an object
Prerequisites: "Constructors"
Instance members: one per object
Every field and method you've written so far — eventName, price, describe() — is an instance member. Each EventTicket object gets its own separate copy of eventName and price; that's why two tickets can have different prices at once.
Static members: one per class, shared by everyone
public class EventTicket {
public String eventName;
public Decimal price;
public static Integer ticketsCreated = 0;
public EventTicket(String eventName, Decimal price) {
this.eventName = eventName;
this.price = price;
ticketsCreated++;
}
}
EventTicket t1 = new EventTicket('Conference', 1200);
EventTicket t2 = new EventTicket('Workshop', 400);
System.debug(EventTicket.ticketsCreated); // 2
ticketsCreated is static, so there is only one copy of it total, shared by every EventTicket object ever created — not one per ticket. It's accessed through the class name (EventTicket.ticketsCreated), not through any specific object.
Static methods: no object required
public class TaxCalculator {
public static Decimal applyVat(Decimal amount) {
return amount * 1.15;
}
}
Decimal total = TaxCalculator.applyVat(100); // 115, no "new" needed
A static method belongs to the class itself, so you call it directly on the class name — TaxCalculator.applyVat(...) — without ever creating a TaxCalculator object. This fits calculations that don't depend on any one object's specific data.
Exercise
Add a static field totalPages to the Book class that accumulates the pageCount of every Book created, updated inside the constructor.
Show hint
public static Integer totalPages = 0; then totalPages += pageCount; inside the constructor.
Static vs Instance Members Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Instance members belong to one specific object; static members belong to the class itself and are shared across every object — and can even be used without creating an object at all.