-1

As everyone knows, Java 9 interfaces will support private method also. So now in interfaces you can declare private method as well as default method. Both the method should have body(I can say it as similarity). I found some questions like this Java 9: private interface methods, example use-case?, didn't found more points.

As per my understanding I found one differences :

default methods of the interfaces are visible in the subclass, where as private method is not visible because of the private modifier.

My question is, any other difference are there apart from that?. When we have to go for private method and default method when designing the API or structure.

Arvind Katte
  • 995
  • 2
  • 10
  • 20

2 Answers2

4

Say you've got an interface with two default methods: a() and b(). The two methods share some common logic, which you can put in a private method c().

In Java8, the above method c() would have to be public, even though it's just an internal implementation of the interface. Before the introduction of private in interfaces, it was harder to write a clean interface with such default methods.

So you shall mark a method private instead of default when the implementation that you're about to put in is specific to the interface itself and not to the outside world implementing it.

Naman
  • 27,789
  • 26
  • 218
  • 353
Gorazd Rebolj
  • 803
  • 6
  • 10
3

things have not changed from a logical point of view for me - when were you using private methods until now? To hide something? To not duplicate the code? Same things stands here - use it when you need to, specifically when there might be code that is common for example for multiple other methods, or simply you want to hide it.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • *To hide something? * got this point. – Arvind Katte Nov 22 '17 at 14:25
  • @ArvindKatte the answer from the link *without exposing that private method and all its "implementation details"* means the same I believe. – Naman Nov 22 '17 at 14:26
  • @nullpointer ah! good point - I haven't read that linked question unfortunately. this indeed looks like a duplicate. But sometimes, me including, find better answers in duplicates; still it seems I add close to nothing added value :| you think we should close this one as such? – Eugene Nov 22 '17 at 14:27