"private static" and "private" methods are added to interface in Java 9. Now private methods can be implemented "static" or "non-static".
Here's the example using default method to access the private non-static method:
- remember if you are using default method, meaning that all of the classes that implement the interfaces can get the result from the private method, but still not able to directly access the private method
- if you are using default to get the result from the private method, you have a choice to make this private static or non staic method.
interface Action{ | |
int miles = 10; | |
void run(int mile); | |
default void speak(){ | |
System.out.println(" I'm speaking from the interface"); | |
} | |
default int getMiles(){ | |
return doubleMile(); | |
} | |
private int doubleMile(){ | |
return miles * 2; | |
} | |
} | |
class Human implements Action { | |
public static void main(String[] args) { | |
Human h = new Human(); | |
h.run(h.getMiles()); | |
} | |
@Override | |
public void run(int mile) { | |
System.out.println("haha I'm running for " + mile + "miles"); | |
} |
Here's the example of using static method to access the result of private static method:
- if you are using static, your private method should also be static
interface Action{ | |
int miles = 10; | |
void run(int mile); | |
default void speak(){ | |
System.out.println(" I'm speaking from the interface"); | |
} | |
static int getMiles(){ | |
return doubleMile(); | |
} | |
private static int doubleMile(){ | |
return miles * 2; | |
} | |
} | |
class Human implements Action { | |
public static void main(String[] args) { | |
Human h = new Human(); | |
h.run(Action.getMiles()); // here's the difference | |
} | |
@Override | |
public void run(int mile) { | |
System.out.println("haha I'm running for " + mile + "miles"); | |
} | |
} |