Sub topic 10
Interface Constants and Implicit Modifiers
When you write an interface, Java adds some words to your code without showing them. These hidden words are called implicit modifiers. A modifier is a keyword such as public, static, or final that changes how a field or method behaves. "Implicit" means Java adds it for you, even if you do not type it.
This chapter covers two things:
- What happens when you put a variable inside an interface.
- Which modifiers Java adds to interface fields and methods, and the errors you get when you forget about them.
Fields in an Interface Are Constants
A constant is a value that never changes after it is set. In Java, any variable you declare inside an interface becomes a constant automatically.
Look at this interface:
interface Limits {
int MAX_USERS = 100;
String APP_NAME = "Tracker";
}It looks like two ordinary fields. Java reads them like this:
interface Limits {
public static final int MAX_USERS = 100;
public static final String APP_NAME = "Tracker";
}Each of the three hidden words has a job:
publicmeans any code can read the value.staticmeans the value belongs to the interface itself, not to an object. You read it asLimits.MAX_USERS.finalmeans the value can never be changed after it is set.
Both versions compile to exactly the same thing. Most Java programmers leave the three words out, because writing them adds nothing.
A Complete Example
interface Limits {
int MAX_USERS = 100;
String APP_NAME = "Tracker";
}
class Account implements Limits {
boolean canAddUser(int currentUsers) {
return currentUsers < MAX_USERS;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Limits.APP_NAME); // prints: Tracker
System.out.println(Limits.MAX_USERS); // prints: 100
Account account = new Account();
System.out.println(account.canAddUser(99)); // prints: true
System.out.println(account.canAddUser(100)); // prints: false
// Limits.MAX_USERS = 200; // compile error: cannot assign a value to final variable MAX_USERS
}
}The Main class reads the constants through the interface name: Limits.APP_NAME. Inside Account, which implements Limits, the short name MAX_USERS also works, because the class inherits the constant.
The commented-out line shows what happens if you try to change a constant. The compiler stops you because the field is final.
Constants Must Be Given a Value
A final field must get a value, and an interface has no constructor that could set it later. So every interface field needs a value right where you declare it.
interface Settings {
int TIMEOUT = 30; // fine
// int RETRIES; // compile error: = expected
}The value can be any expression Java can work out when the interface loads, such as int TIMEOUT_MS = 30 * 1000;.
Methods in an Interface Are Public and Abstract
Fields are not the only members with hidden modifiers. A method without a body in an interface is treated as public abstract.
| What you write | What Java reads |
|---|---|
| `int MAX = 5;` | `public static final int MAX = 5;` |
| `void start();` | `public abstract void start();` |
| `interface Shape { }` nested inside an interface | `public static interface Shape { }` |
| `class Helper { }` nested inside an interface | `public static class Helper { }` |
The default, static, and private methods that newer versions of Java allow in interfaces have their own rules. Later chapters cover them.
The Most Common Mistake: Forgetting `public`
Interface methods are always public. A class method with no access modifier is package-private, which means only code in the same package can call it. If you implement an interface method and leave out public, you make the method less visible than the interface promised. Java does not allow that.
interface Greeter {
String greet(String name); // really: public abstract
}
class FriendlyGreeter implements Greeter {
// String greet(String name) { ... }
// compile error: attempting to assign weaker access privileges; was public
@Override
public String greet(String name) {
return "Hello, " + name + "!";
}
}
public class Main {
public static void main(String[] args) {
Greeter g = new FriendlyGreeter();
System.out.println(g.greet("Ana")); // prints: Hello, Ana!
}
}The fix is always the same: write public on the method in your class.
Modifiers You Cannot Use
Some modifiers clash with the hidden ones, so the compiler rejects them:
private int x = 1;as a field fails, because interface fields must be public.protected void run();fails, because interface methods cannot be protected.final void run();fails, because afinalmethod could never be implemented.
Writing a hidden modifier on purpose is allowed. public abstract void run(); compiles fine. It just repeats what Java already assumes.
Edge Case: Final Does Not Mean Frozen
final stops you from pointing the name at a different value. It does not stop you from changing the inside of an object. Arrays show this clearly:
interface Defaults {
int[] SIZES = {1, 2, 3};
}
public class Main {
public static void main(String[] args) {
// Defaults.SIZES = new int[] {9}; // compile error: final variable
Defaults.SIZES[0] = 99; // allowed: changes the contents
System.out.println(Defaults.SIZES[0]); // prints: 99
}
}Any code anywhere can change this "constant" array, because it is also public. Use interface constants for values that cannot change, such as numbers and strings. Strings in Java are immutable, which means their contents can never change.
Edge Case: The Constant Interface Problem
Some older code creates an interface that holds only constants, and classes implement it just to use the short names. This habit is known as the constant interface anti-pattern. An anti-pattern is a common way of doing something that causes problems.
The trouble is that implements makes a public promise about what a class is. A class that implements Limits only to type MAX_USERS instead of Limits.MAX_USERS now tells every user that it "is a" Limits. That claim means nothing, and it cannot be removed later without breaking other code.
A better home for a group of constants is a final class with a private constructor:
final class AppConstants {
private AppConstants() { } // no objects allowed
static final int MAX_USERS = 100;
static final String APP_NAME = "Tracker";
}
public class Main {
public static void main(String[] args) {
System.out.println(AppConstants.APP_NAME); // prints: Tracker
}
}A constant belongs in an interface when it is part of what the interface means. For example, a Timer interface could reasonably hold a MAX_DELAY value.
Exercises
Exercise
An interface contains the line double RATE = 0.05;. Which three modifiers does Java add to this field, and how would code outside the interface read it if the interface is named Bank?
Show answer
Java adds public, static, and final, so the field is a public constant that belongs to the interface. Outside code reads it as Bank.RATE.
Exercise
This code does not compile. Why, and how do you fix it? interface Task { void run(); } class PrintTask implements Task { void run() { System.out.println("run"); } }
Show answer
Task's run() is implicitly public abstract. In PrintTask, run() has no access modifier, so it is package-private, which is weaker than public. The compiler reports "attempting to assign weaker access privileges". The fix is to declare it as public void run().
Exercise
Will the line int LIMIT; compile inside an interface? Explain.
Show answer
No. Interface fields are implicitly final, and a final field must be given a value. An interface has no constructor to assign it later, so the value must appear on the same line, for example int LIMIT = 10;.
Exercise
An interface declares String[] NAMES = {"a", "b"};. Can other code run NAMES[0] = "z";? Can it run NAMES = new String[0];?
Show answer
The first line is allowed, because final only fixes which array the name refers to, not what the array contains. The second line is a compile error, because it tries to point a final variable at a new array.