Interface constants
- Java course
- Intermediate
- Lesson 39/116
- 5 min
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.
Practice 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.
Starter code
// Define the Keys interface
// Add two constants
// Print in mainSample 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);
}
}Expected output
Enter Esc
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the interface constant
interface Config {
int ____ = 100;
}
interface Config {
int MAX = 100;
}
Explanation: Interface constants are uppercase.
2 Match interface constant properties
| Term | Meaning |
|---|---|
public |
Accessible everywhere |
static |
Class level |
final |
Immutability |
automatic |
Applies without writing |
3 In: interface Config { int MAX = 10; }, what access does MAX have?
- protected
- package-private
- public static final Correct answer
- private
Explanation: Public static final — interface fields automatically get this access.