Beginner · Classes and objects · topic 19 of 60 · 20 min
static members and final
Explanation
static fields: one copy for the whole class
public class Ticket {
private static int issued = 0; // shared by ALL tickets
private final int number; // each ticket has its own
public Ticket() {
issued++;
number = issued;
}
public int getNumber() { return number; }
public static int getIssued() { return issued; } // static method
}
new Ticket(); new Ticket(); Ticket t3 = new Ticket();
System.out.println(t3.getNumber()); // 3
System.out.println(Ticket.getIssued()); // 3 (called on the class)static methods
A static method does not run on an object, so it has no this and cannot use instance fields directly. It is ideal for utility functions that only need their parameters: Math.sqrt, Integer.parseInt, Arrays.sort. That is also why main is static: the JVM can call it before any object exists.
public final class GstUtil {
private GstUtil() {} // no objects of a utility class
public static final double STANDARD_RATE = 18.0; // a constant
public static double withGst(double amount) {
return amount * (1 + STANDARD_RATE / 100);
}
}
double total = GstUtil.withGst(1000); // 1180.0Constants: public static final
A constant is a value that never changes and is the same for everyone: public static final int MAX_LOGIN_ATTEMPTS = 3;. Name constants in UPPER_SNAKE_CASE. For a group of related constants (payment modes, order statuses), an enum is usually better.
final in three places
| Where | Meaning | Example |
|---|---|---|
| final variable / field | Can be assigned only once | final String owner; |
| final method | Subclasses cannot override it | public final void audit() |
| final class | No class can extend it | public final class String |
final on a reference variable means the variable cannot point to another object, NOT that the object cannot change: final List<String> list = new ArrayList<>(); list.add("x"); is fine.
static blocks (in brief)
A static { … } block runs once when the class is first loaded, for complex static initialisation such as loading a table of rates. Use it sparingly.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
static members and final · 1/6
In this lesson you will learn what static and final mean.
Prefer a video by a teacher? Find free videos on “java static keyword final keyword explained” on YouTube ↗
In real life: Invoice numbers for a shop
A billing app numbers invoices INV-0001, INV-0002… A static counter in the Invoice class is shared by every invoice object, so each new invoice gets the next number. (In a real multi-user system the number would come from the database.)
public class Invoice {
private static int counter = 0;
private final String number;
public Invoice() { counter++; number = String.format("INV-%04d", counter); }
public String getNumber() { return number; }
}
// new Invoice().getNumber() → "INV-0001", the next one → "INV-0002"Practice (0/3 done)
What does this print? class C { static int s = 0; int i = 0; C() { s++; i++; } } … new C(); new C(); C c = new C(); System.out.println(C.s + " " + c.i);
Which line gives "non-static method show() cannot be referenced from a static context"? class App { void show() {} public static void main(String[] a) { show(); // line X new App().show(); // line Y } }
Write a utility class TempUtil with a private constructor, a constant ABSOLUTE_ZERO_C = -273.15, and static methods cToF(double) and fToC(double). Call them from main without creating an object.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- toString, equals, hashCode and recordsClasses and objects · same module
- Constructors and thisClasses and objects · same module
- Access modifiers, static members and encapsulationC# and .NET · Classes and objects
- Classes and objects: data plus behaviourC++ Programming (modern C++ and DSA) · Classes, constructors and RAII
- ClassesJavaScript Programming (language in depth) · Scope, this, prototypes and classes
- Data, enum and sealed classes, and objectsKotlin and Android App Development · Classes, objects and collections
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Why is main declared static?
Answer: So the JVM can call it without creating an object
No object exists when the program starts.
final List<String> list = new ArrayList<>(); list.add("a"); Does this compile?
Answer: Yes: final stops reassignment, not changes to the list
The reference is final; the object is still mutable.
Which class is final in the JDK?
Answer: String
String is final, so nobody can subclass it.
How do you usually call a static method?
Answer: ClassName.method()
Static members belong to the class.
Two objects of the same class…Related
Answer: Each have their own copies of instance fields
Instance fields belong to each object.
From Classes and objects
How do you call a static method Fare on class MetroCard?Related
Answer: MetroCard.Fare(3)
Static members are reached through the class name.
A static member variable is…Related
Answer: shared by the whole class, one copy in total
Static members belong to the class, not to individual objects.
How is a static method called?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Classes and objects” before its exam: toString, equals, hashCode and records.
- Module 4 exam: Classes and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Inheritance, polymorphism and interfaces. 60 topics left in the course before the final exam.
← Previous: Encapsulation: private fields, getters and setters