Why doesn't Java allow private members in interface? Is there any particular reason?
From Java 9, private methods can be added to interfaces in Java.
Private method can be used only inside interface and other static and non-static interface methods. Private non-static methods cannot be used inside private static methods.
Interfaces are meant to define the public API of a type - and only that, not its implementation. So any method (or static member) you define in an interface is by definition public . Since an interface can't contain any concrete implementation, there is no way to call any member methods from within.
Protected methods are intended for sharing implementation with subclasses. Interfaces have nothing to offer as far as implementation sharing goes, because they have no implementation at all. Therefore all methods on interfaces must be public.
From the Java Language Spec, (Access Control):
"The Java programming language provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class."
Access control is all about hiding implementation details. An interface has no implementation to hide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With