Java
Summary - Static
Combine static fields, methods and blocks to write a Configuration class.
Summary - Static
In this group you learned static fields, static methods, static blocks, class variables and the instanceof operator. Static members belong to the class; they are used without an instance.
Now you will bring it all together: define a class, add static fields and methods, initialize with a static block and check types with instanceof. Static provides class-level shared data and behavior.
Exercise Define Logger with static
Define a class Logger. Add a static int count = 0 field. Write a static void log(String msg) method; its body runs count++ and System.out.println(count + ": " + msg);. In main call Logger.log("Started") and Logger.log("Done").
Show example solution
class Logger {
static int count = 0;
static void log(String msg) {
count++;
System.out.println(count + ": " + msg);
}
public static void main(String[] args) {
Logger.log("Started");
Logger.log("Done");
}
}
What comes next?
You learned static members. In the next groups you will define immutable values with constants, constant sets with enum and contracts with interfaces. These are the next layer of class design.
This group combined static fields, methods, blocks, class variables and instanceof. These are the basics of working at the class level. Next you will define immutable values with constants; you will explore immutable data with static final and enum.
Exercise Define Counter with static
Define a class Counter. Add a static int total = 0 field. Write a static void increment() method; its body runs total++. Write a static int getTotal() method returning total. In main call Counter.increment() three times and print the result of Counter.getTotal().
Show example solution
class Counter {
static int total = 0;
static void increment() {
total++;
}
static int getTotal() {
return total;
}
public static void main(String[] args) {
Counter.increment();
Counter.increment();
Counter.increment();
System.out.println(Counter.getTotal());
}
}
Test yourself
-
How is a static method called?
- Inside a constructor
- Through the class name
- Through an instance
- With an interface
Show answer
Through the class name — Through the class name — a static method needs no instance.
-
Complete the instanceof check
if (obj ____ String) {
String s = (String) obj;
}
Show answer
if (obj instanceof String) {
String s = (String) obj;
}
Next lesson: static final