Sub topic 14
Private Helper Methods in Interfaces
In the last two chapters you added default methods and static methods to interfaces. A default method is an interface method that has a body, so implementing classes get it for free. A static method belongs to the interface itself, and you call it through the interface name.
Once an interface has several default methods, you may notice that some of them repeat the same lines of code. This chapter shows how Java 9 lets you move that shared code into a private method. A private method is a method that only code inside the same interface can call.
The Problem: Repeated Code in Default Methods
Here is a logging interface with two default methods. Both of them build a message the same way.
interface Logger {
void log(String message);
default void info(String message) {
log("[" + "INFO" + "] " + message);
}
default void warn(String message) {
log("[" + "WARN" + "] " + message);
}
}The formatting code appears twice. Suppose you later want to add a time stamp to every line. You would have to change both methods, and it is easy to forget one.
You could fix this with a new default method called format. But a default method is public, which means any code that has a Logger can call it. That makes format part of the interface's promise to the world, even though it is only a helper. Other classes could start to depend on it, and then you could never change or remove it safely.
What you want is a helper that the interface can use but nobody else can see. A private method gives you exactly that.
Declaring a Private Interface Method
Since Java 9, you can write private in front of a method inside an interface. The method must have a body. Here is the logger again, with the shared code moved into a private helper.
interface Logger {
void log(String message);
default void info(String message) {
log(format("INFO", message));
}
default void warn(String message) {
log(format("WARN", message));
}
private String format(String level, String message) {
return "[" + level + "] " + message;
}
}
class ConsoleLogger implements Logger {
@Override
public void log(String message) {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
Logger logger = new ConsoleLogger();
logger.info("Started"); // prints: [INFO] Started
logger.warn("Low disk space"); // prints: [WARN] Low disk space
}
}Here is what each part does:
logis the abstract method.ConsoleLoggermust supply its body.infoandwarnare default methods. They are public, so callers can use them.formatis private. Onlyinfo,warn, and other code insideLoggercan call it.
Now the format lives in one place. To add a time stamp, you change only format.
Private Static Helper Methods
A private method can also be static. You use a private static method when the helper is shared by static methods of the interface.
interface Stats {
static double average(int[] values) {
if (values.length == 0) {
return 0.0;
}
return (double) sum(values) / values.length;
}
static int total(int[] values) {
return sum(values);
}
private static int sum(int[] values) {
int result = 0;
for (int v : values) {
result += v;
}
return result;
}
}
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
System.out.println(Stats.total(scores)); // prints: 270
System.out.println(Stats.average(scores)); // prints: 90.0
}
}Both average and total need to add up the numbers, so the loop lives in sum. Code outside the interface cannot write Stats.sum(scores). That line would not compile.
Who Can Call What
Interface methods follow one key rule. A static method has no object to work with, so it cannot call a non-static method. A default or private instance method runs on an object, so it can call both kinds.
This table sums up the rules.
| Caller | Private instance method | Private static method |
|---|---|---|
| Default method in the same interface | Yes | Yes |
| Private instance method in the same interface | Yes | Yes |
| Static method in the same interface | No | Yes |
| Implementing class | No | No |
| Any other code | No | No |
Common Mistakes
Trying to call the helper from the implementing class
A private method is not inherited. The class that implements the interface cannot see it.
interface Greeter {
default String greet(String name) {
return wrap("Hello, " + name);
}
private String wrap(String text) {
return "*** " + text + " ***";
}
}
class FriendlyGreeter implements Greeter {
String shout(String name) {
// return wrap(name.toUpperCase()); // compile error: wrap() is private in Greeter
return greet(name.toUpperCase()); // fine: greet() is a public default method
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new FriendlyGreeter().shout("sam")); // prints: *** Hello, SAM ***
}
}If the class really needs that behavior, call the public default method that uses the helper, as shout does here.
Leaving out the body
A private method must have a body. The line private String wrap(String text); is a compile error. An abstract method is something another class must fill in, and no other class can see a private method, so a private abstract method would make no sense.
Mixing private with default or abstract
You cannot write private default or private abstract. A default method is always public. Use private alone for an instance helper, or private static for a static helper.
Calling a private instance method from a static method
interface Shapes {
static String label() {
// return name(); // compile error: cannot call a non-static method from a static context
return "shape";
}
private String name() {
return "shape";
}
}If a static method needs the helper, declare the helper private static.
When to Use a Private Helper
Use a private interface method when:
- Two or more default or static methods share the same steps.
- The shared steps are an inside detail, and users of the interface should not rely on them.
- You want to change the helper later without breaking any class that implements the interface.
If the helper is something callers should use, make it a public default or static method instead.
Exercise
An interface Formatter has a static method static String bold(String s) that needs a helper to wrap text in a symbol. Should the helper be declared private or private static, and why?
Show answer
It should be private static. A static method has no object to call an instance method on, so it can only call other static methods. A plain private helper would cause a compile error when bold calls it.
Exercise
A class FileLogger implements Logger, where Logger has a private method format(String level, String message). Can FileLogger call format("ERROR", "Disk full") inside its own log method? What should it do instead?
Show answer
No. Private interface methods are not inherited, and only code inside Logger can see them, so the call is a compile error. FileLogger should call a public method that uses the helper, such as info or warn, or it should build the text itself.
Exercise
Rewrite this interface so the repeated code lives in one private helper: interface Money { double amount(); default String asDollars() { return "$" + String.format("%.2f", amount()); } default String asEuros() { return "€" + String.format("%.2f", amount() * 0.9); } }
Show answer
Add private String show(String symbol, double value) { return symbol + String.format("%.2f", value); } and change the defaults to default String asDollars() { return show("$", amount()); } and default String asEuros() { return show("€", amount() * 0.9); }. The helper is an instance method, which default methods are allowed to call.