Private Interface Methods Share Defaults
Keep helper logic inside the interface with private methods: callable from default and static members, invisible to implementing classes, never inherited.
Code
public interface ValidationRules {
// default 方法之间的公共逻辑收进 private 方法:实现类看不到也改不掉
default boolean isAdult(int age) {
return inRange(age, 18, 150);
}
default boolean isRetirementAge(int age) {
return inRange(age, 65, 150);
}
// private 实例方法:JLS 9.4(Java 9+),不能与 abstract/default 混用
private boolean inRange(int value, int min, int max) {
return value >= min && value <= max;
}
// private + static 也合法:既不被继承也不能被重写
private static String label(boolean ok) {
return ok ? "pass" : "fail";
}
static String describe(boolean ok) {
return "rule: " + label(ok); // 接口内的 static 方法可调用私有 static
}
}
class RuleDemo implements ValidationRules {
public static void main(String[] args) {
RuleDemo demo = new RuleDemo();
System.out.println("adult(20): " + demo.isAdult(20));
System.out.println("retirement(20): " + demo.isRetirementAge(20));
System.out.println(ValidationRules.describe(true));
}
}What the code does
Private Interface Methods Share Defaults is built around the classes ValidationRules and RuleDemo and the functions inRange, label, describe and main.
Watch out for
- The project needs no additions before running it.
Using it
The signature you will reach for first is private boolean inRange(int value, int min, int max)
The run emits 2 labeled sections — adult(20):, retirement(20): — one per step.
Launch the file; main takes over and steps through describe.
Key statements
return "rule: " + label(ok); // 接口内的 static 方法可调用私有 static
}
return value >= min && value <= max;
return inRange(age, 18, 150);
Interactive Tools for This Topic
FAQ
- What does Private Interface Methods Share Defaults print when run?
- The script runs standalone; its 2 labeled outputs include `adult(20):`, `retirement(20):`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.