Java Reference ยท Object-Oriented Concepts
Private interface methods
Private and private static interface methods in Java 9+: why they exist, how to share code between default methods, and the rules that apply.
Java 9 allows interface methods to be private. A private interface method has a body, can only be called from inside the interface itself, and is invisible to implementing classes and callers. Its purpose is to remove duplication between default and static methods without turning the shared helper into part of the public API.
Before Java 9 you had two bad options: copy the shared code into each default method, or add a public method that every implementor would inherit and that clients could call.
interface Formatter { private String clean(String s) { return s.strip(); } // instance helper private static String quote(String s) { return "'" + s + "'"; } default String show(String s) { return quote(clean(s)); } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Rules
| Kind | Allowed? | Can be called from |
|---|---|---|
private instance method (with body) |
Yes, since Java 9 | default methods and other private instance methods |
private static method (with body) |
Yes, since Java 9 | default, static and private methods |
private abstract method |
No | none: a private method must have a body |
private default method |
No | the two modifiers contradict each other |
protected or package-private method |
No | interface members are public or private only |
Usage notes
- A private instance method has access to
this, so it can call the interface's abstract and default methods. - They are not inherited and cannot be overridden. A class that happens to declare a method with the same name creates an unrelated method, as the second example shows.
- Use them for code shared by two or more defaults. If only one default method needs the code, inline it.
- Not part of the contract. You can rename or remove a private method without breaking implementors, which is the main benefit.
- Reflection can still list private interface methods through
getDeclaredMethods(), as the example shows. - Interface fields remain constants. Private methods do not give interfaces mutable state.
- JDK 8 compatibility: code using private interface methods needs release 9 or newer; the site's runner uses Java 25, so it works.