Lesson 18 of 20
Static & Final
Static & Final Keywords
Static Fields and Methods
A static member belongs to the class rather than any instance. You access it via the class name:
class Counter {
static int count = 0;
Counter() { count++; }
static int getCount() { return count; }
}
new Counter();
new Counter();
System.out.println(Counter.getCount()); // 2
Static methods cannot access instance fields or use this.
Final Variables
A final variable can only be assigned once. It acts as a constant:
final int MAX = 100;
// MAX = 200; // compile error!
final String name;
name = "Alice"; // OK — first assignment
// name = "Bob"; // compile error — already assigned
Final Methods and Classes
- A
finalmethod cannot be overridden in a subclass. - A
finalclass cannot be extended at all (e.g.Stringis final).
class Base {
final void greet() {
System.out.println("Hello");
}
}
Static Factory Pattern
Instead of public constructors, use static factory methods for more readable, controlled object creation:
class Color {
private final int r, g, b;
private Color(int r, int g, int b) {
this.r = r; this.g = g; this.b = b;
}
static Color of(int r, int g, int b) {
return new Color(r, g, b);
}
static Color red() { return new Color(255, 0, 0); }
static Color green() { return new Color(0, 255, 0); }
}
Your Task
-
Create a class
IdGeneratorwith:- A
private static int nextIdstarting at 0 - A
static int generate()method that increments and returnsnextId - A
static void reset()method that setsnextIdback to 0
- A
-
Create a class
Temperaturewith:- A
private final double valueandprivate final String unitfield - A private constructor
- Static factory methods
celsius(double v)andfahrenheit(double v) - A
toString()method returning e.g."36.6 C"or"98.6 F" - A
toFahrenheit()method that returns a newTemperaturein Fahrenheit (if already F, return itself). Formula:value * 9 / 5 + 32
- A
-
In
main, generate 3 IDs (print each), reset, generate 1 more (print it). Then create a Celsius temperature of 100.0 and a Fahrenheit temperature of 98.6, print both, and convert the Celsius one to Fahrenheit and print it.
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.