Java
Summary - Constants
Combine static final and enum constants to write a unit conversion class.
Summary - Constants
In this group you learned static final constants, the uppercase naming convention, constant sets with enum, interface constants and the ready-to-use constants of the Math class. Constants manage immutable values from a single point.
Now you will bring it all together: define constants, create constant sets with enum and calculate with Math constants. Constants are the foundation of robust code design.
Exercise Define Circle with the Math constant
Define a class Circle. Add a double radius field. Write a Circle(double r) constructor; assign radius = r;. Add a double area() method returning Math.PI * radius * radius. In main create an instance with new Circle(5.0) and print the result of area().
Show example solution
class Circle {
double radius;
Circle(double r) {
radius = r;
}
double area() {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
Circle c = new Circle(5.0);
System.out.println(c.area());
}
}
What comes next?
You learned constants. In the next groups you will define contracts with interfaces, create shared structure with abstract classes and provide flexible behavior with polymorphism. These are the upper layer of object-oriented design.
This group combined static final, the uppercase convention, enum, interface constants and Math constants. These are the foundation of immutable data management. Next you will define contracts with interfaces; you will declare methods that classes must implement.
Exercise Define Status enum and Constants class
Define an enum named Status with ACTIVE, PAUSED, STOPPED constants. Define a class Constants with a static final int MAX_RETRY = 3 constant. In a main method write Status s = Status.ACTIVE; and print Constants.MAX_RETRY and s on separate lines.
Show example solution
enum Status { ACTIVE, PAUSED, STOPPED }
class Constants {
static final int MAX_RETRY = 3;
public static void main(String[] args) {
Status s = Status.ACTIVE;
System.out.println(Constants.MAX_RETRY);
System.out.println(s);
}
}
Test yourself
-
What format are constant names written in?
- camelCase
- UPPER_SNAKE_CASE
- PascalCase
- lowercase
Show answer
UPPER_SNAKE_CASE — UPPER_SNAKE_CASE — constants are uppercase.
-
Complete the enum definition
enum Color {
RED, GREEN, ____
}
Show answer
enum Color {
RED, GREEN, BLUE
}
Next lesson: Quiz model