For Java 9 and on, I understand that private
interface methods can be declared and implemented in the interface, then called by default
interface methods (of the same interface).
But, private
interface methods cannot be called by static
interface methods.
Now, I also understand that private static
interface methods can be declared/implemented in the interface, then called by default
as well as static
methods.
So it seems to me that the abilities of a private static
interface method is a 'superset' of a private
interface method.
If that is the case, is there any situation where using a private
interface method is preferable to using a private static
interface method?
For example:
public interface Schedule {
default void wakeUp() { checkTime(7); }
// static void sleep() { checkTime(21); } // compile error if private interface method called
private void checkTime(int time) { // if so, why not always use private static method instead?
// implementation omitted
}
}
A non-static method can itself call other instance methods.
public interface Schedule {
LocalTime getCurrentTime();
default void wakeUp() { checkTime(7); }
private void checkTime(int time) {
if (getCurrentTime().isAfter(/*something*/)) {
// do something
}
}
}
If it were static, it couldn't do that. If you don't need to call another instance method, make it static.
This is pretty much the same logic you should follow when writing a normal class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.