Summary - Static
- Java course
- Intermediate
- Lesson 35/116
- 5 min
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.
Practice 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").
Starter code
// Define the Logger class
// Add a static count field and log method
// Call log in mainSample 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");
}
}Expected output
1: Started 2: 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.
Practice 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().
Starter code
// Define the Counter class
// Add static total, increment and getTotal
// Call increment and print getTotal in mainSample 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());
}
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a static method called?
- Inside a constructor
- Through the class name Correct answer
- Through an instance
- With an interface
Explanation: Through the class name — a static method needs no instance.
2 Complete the instanceof check
if (obj ____ String) {
String s = (String) obj;
}
if (obj instanceof String) {
String s = (String) obj;
}
Explanation: instanceof safely checks the type.