Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java allow private members in interface?

Tags:

java

Why doesn't Java allow private members in interface? Is there any particular reason?

like image 556
dpp Avatar asked Apr 16 '12 06:04

dpp


People also ask

Can Java interface have private methods allowed?

From Java 9, private methods can be added to interfaces in Java.

Can private be used in interface?

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.

Why members of Java interface are public by default?

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.

Why interface Cannot have protected methods?

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.


1 Answers

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.

like image 145
Matten Avatar answered Oct 20 '22 15:10

Matten