Java
Interface constants
Learn to define constants inside interfaces.
Interface constants
An interface can contain static final constants. Fields in interfaces are automatically public static final; these keywords apply even if you do not write them. This feature is used to group related constants together.
Example: interface Config { int MAX = 100; String NAME = "App"; }. Here MAX and NAME are automatically public static final. They are accessed as Config.MAX. Interface constants group related values under one umbrella. However, modern Java prefers enums or classes with static final for grouping constants; interface constants are an older approach.
Automatic public static final
Fields inside an interface automatically have public static final access even if you do not write these keywords. This guarantees that interface constants are accessible everywhere, at the class level and immutable.
Example: interface Keys { String ENTER = "Enter"; }. Here ENTER does not have public, static or final written, but all three apply. Keys.ENTER is accessible from everywhere; the value cannot be changed. This automatic behavior keeps interface constants consistent. Modern Java still supports this feature, but enums or classes are more commonly preferred for grouping constants.
Exercise Add constants to the Keys interface
Define an interface named Keys. Add String ENTER = "Enter" and String ESC = "Esc" constants. In a main method print both constants' values on separate lines.
Show example solution
interface Keys {
String ENTER = "Enter";
String ESC = "Esc";
}
public class Main {
public static void main(String[] args) {
System.out.println(Keys.ENTER);
System.out.println(Keys.ESC);
}
}
Test yourself
-
Complete the interface constant
interface Config {
int ____ = 100;
}
Show answer
interface Config {
int MAX = 100;
}
-
Match interface constant properties
- public
- Accessible everywhere
- static
- Class level
- final
- Immutability
- automatic
- Applies without writing
-
In: interface Config { int MAX = 10; }, what access does MAX have?
- protected
- package-private
- public static final
- private
Show answer
public static final — Public static final — interface fields automatically get this access.
Next lesson: Math constants