92

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

th3morg
  • 4,321
  • 1
  • 32
  • 45
kazinix
  • 28,987
  • 33
  • 107
  • 157
  • @pst I wrote a workaround at the end of my answer - http://stackoverflow.com/a/10169894/348975. Does it address your concerns? – emory Apr 16 '12 at 07:19
  • Java 9 onwards its allowed. Check my answer below: https://stackoverflow.com/questions/10169654/why-doesnt-java-allow-private-members-in-interface/43319103#43319103 – akhil_mittal Jul 06 '20 at 11:12
  • To future readers: as it's currently written, the OP asks for private *members*, this is not limited to *fields*, but also includes methods. – MC Emperor May 17 '22 at 13:34

14 Answers14

89

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.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
Matten
  • 17,365
  • 2
  • 42
  • 64
  • 9
    Since we can put nest classes inside an interface, we can put implementation on the interface. Doing so is very wrong, but we can. – emory Apr 16 '12 at 07:11
  • 36
    Java 9 allows private methods in interface, It is logical after the addition of default methods, Ref: https://bugs.openjdk.java.net/browse/JDK-8071453 – Hariharan May 05 '15 at 06:15
  • 6
    "Doing so is very wrong"..as always, depends on the context. – JacksOnF1re Aug 11 '17 at 09:59
  • 8
    It's not that bad as it sounds. The private methods in an interface can only be accessible by default methods in that same interface. One of the benefits is to help breaking implementation of default methods into meaningful smaller functions without breaking encapsulation. – Henry Pham Sep 22 '17 at 07:32
53

In Java 9, private methods in interfaces are possible.

Java 9 specifications

The javac compiler team is pleased announce the availability of compiler support for private methods in interfaces beginning with 9 b54 build of JDK.

chiperortiz
  • 4,751
  • 9
  • 45
  • 79
19

Private interface methods are part of Java 9 as part of JEP-213. Since interfaces in Java 8 can have default methods, private methods allow for multiple default methods to use a shared private method.

mkobit
  • 43,979
  • 12
  • 156
  • 150
15

As of Java 8, interfaces can have default methods, and as of Java 9, an interface is allowed to have a private methods which can only be accessed by default methods in the same interface.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
10

An interface is used for describing an API which is provided by any class implementing the interface. Since an interface from its definition has no state there is no use of declaring field members in it.

giorashc
  • 13,691
  • 3
  • 35
  • 71
7

There would be no way to implement such an interface. An answer to a question I posed strongly suggests that it would be impossible (without radically changing the rules) to implement an interface with private methods - this leaves open the question of why protected and package private methods are not allowed.

class OuterClass
{
     void run ( MyInterface x )
     {
           x . publicMethod ( ) ;  // why not?
           x . protectedMethod ( ) ; // why not?
           x . packagePrivateMethod ( ) ; // why not?
           x . privateMethod ( ) ; // why not?
     }

     interface MyInterface
     {
           public abstract void publicMethod ( ) ; // OK

           protected abstract void protectedMethod ( ) ; // why not?

           abstract void packagePrivateMethod ( ) ; // in interface default is public, but why not package private

           private void privateMethod ( ) ; // impossible to implement
     }

     class MyImpl implements MyInterface
     {
           public void publicMethod ( ) { } // ok

           protected void protectedMethod ( ) { } // no sweat

           void packagePrivateMethod ( ) { } // no sweat

           private void privateMethod ( ) { } // not happening
     }
}

The below code should achieve the desired result. Even though all methods are public, only public method is effectively public. protected method is effectively protected. packagePrivateMethod is effectively packagePrivate. privateMethod is effectively private.

class WorkAround
{
     void run ( MyPrivateInterface x )
     {
           x . publicMethod ( ) ;  
           x . protectedMethod ( ) ; 
           x . packagePrivateMethod ( ) ; 
           x . privateMethod ( ) ; 
     }

     public interface MyPublicInterface { void publicMethod ( ) ; }

     protected interface MyProtectedInterface extends MyPublicInterface { void protectedMethod ( ) ; }

     interface MyPackagePrivateInterface extends MyProtectedInterface { void packagePrivateMethod ( ) ; }

     private interface MyPrivateInterface extends MyPackagePrivateInterface { void privateMethod ( ) ; }
}
Community
  • 1
  • 1
emory
  • 10,725
  • 2
  • 30
  • 58
6

According to the Java programming language scope of the private members is limited to the class in which it is declared and can be accessed only by methods of that class. But inteface doesn't have a method body hence there is no use of declaring private members inside an interface.

Nishant
  • 32,082
  • 5
  • 39
  • 53
5

Java allows private methods in an interface in Java 9. The default methods were introduced in Java 8. It is possible that multiple default methods want to share some code, then this code can be moved to a private method without exposing it to outer world. This bug has been fixed and starting in JDK 9 build 54, compiler support for private interface methods have been resurrected.

public interface IData{
   default void processData(int data) {
      validate(data);
      // do some work with it
   }
   default void consumeData(int data) {
      validate(data);
      // do some work with it
   }
   private void validate(int data) {
     // validate data
   }
}
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
3

It is because they would be useless.

There would be no way to call a private method.

Private members are an implementation detail. An interface is about the public role that a class can take on.

WW.
  • 23,793
  • 13
  • 94
  • 121
  • I disagree wrt "There would be no way to call a private method." With the inner classes, there would be a way - http://stackoverflow.com/a/10169894/348975 – emory Apr 16 '12 at 07:05
  • Consider default methods of java 8. Interface I has default methods A and B with a lot of common code. To refactor this you would want method C that would contain just the shared code and being called by A and B. In Java 8 this would be a default method that is exposed to all interface implementors. in Java 9 C could be a private method visible only to default methods within I. – Ivan Krylov Oct 20 '15 at 10:39
2

private fields would not be completely useless as other fields and inner classes could access them.

However private methods could not be implemented, even in nested classes, making them almost useless. You could read them using reflection, but that is rather an edge case.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Sorry for grave-digging here :( How does https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html work in this case? Can't people implement it and then overwrite the readObject and writeObject methods? I'm sure I'm missing something – PatrickWalker Jun 13 '17 at 13:39
1

Private members don't make sense in interface. Interface is a way to access a class with defined methods where you don't need to see the inners of that class.

Private members disagree to that.

juergen d
  • 201,996
  • 37
  • 293
  • 362
0

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

Source

So you don't have any working methods in an interface which can work with that private non-inheritable field, Then why should it exist?

Community
  • 1
  • 1
Alireza Mohamadi
  • 511
  • 5
  • 19
0

Yep, can't do that. For all those commenting on why it shouldn't:

Imagine I have Class A, which utilizes interface I. Class B, extends Class A, therefore also inheriting all interface methods in A.

Now, imagine I want a private method in Class A, but want it contractually defined for other classes as well (Maybe a class C, which doesn't necessarily extend Class B or A).

Perhaps for an "initialization" method, that I want for all classes using an I interface. But obviously I don't want an initialization method to be public.... since it should only be used once, or as the class deems necessary, not just because you want to use it all willy-nilly.

The only solution is a workaround, or by simply forcing the init method into the classes themselves without an interface.

I understand the reason not too, for sure, but still, it can come in handy sometimes. Clearly Oracle agrees as they're allowing private interface methods in JDK 9.

What I did, for mine anyway, was place a simple boolean variable, that way the interface method (which should be private) can be flagged as true (initialized = true) after being set once. Then when called again the method simply does nothing. This way the interface method can be implemented as public, but since the constructor (of my class) calls the method first, this sets the variable to true, and so it can't be called again.

Otherwise you'd have to try a different workaround if you only want the inner workings of the class to use it.... perhaps a method itself sets a flag on and off as it uses it. When the flag is false, the method does nothing (this would be when someone calls it from outside the class). However, when the classes own methods call it, they quickly set the flag to true, then call the method, then set the flag to false??

In the end kind of mute. Probably just better for now to simply place the private class into the class itself and cut-out the interface altogether.

0

Interfaces can't have private members, which includes data variables \ fields as well as methods.

Here is a timeline of how Java interfaces have evolved (source):

  • Java 1.1
    • Nested classes
    • Nested interfaces
  • Java 5
    • Generics
    • Nested enums
    • Nested annotations
  • Java 8
    • Default methods
    • Static methods
  • Java 9
    • Private methods

With the current implementation If the interface members are private, you cannot provide implementation to the methods or cannot access the fields in the implementing class. Therefore, the members of an interface cannot be private. If you try to declare the members of an interface private, a compile-time error is generated saying “modifier private not allowed here”.

boardtc
  • 1,304
  • 1
  • 15
  • 20