3

I use Java but I have a better background with C#. I've been reading Java's default and static methods in interfaces. I think I understood how default methods in interfaces would be useful. For instance, we have extension methods in C#. One thing it helps language designers is that they could freely add new methods for interfaces such as Where, Select, etc. where lambda expressions can be used without breaking binary code compatibility. So default methods in Java's interfaces can help in the same way.

But when it comes to static methods in Java interfaces, it is where I am not sure how useful it would be. Can anyone explain me why static methods added to interfaces and in what cases they are useful for us developers. I also would like to hear if there are different reasons for default method other than what I mentioned.

Community
  • 1
  • 1
Tarik
  • 79,711
  • 83
  • 236
  • 349
  • @tambykojak It seems you can add static methods to interfaces. Please check out this link: http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html and scroll down little to see Static Methods section. – Tarik Apr 24 '14 at 00:03

1 Answers1

3

But when it comes to static methods in Java interfaces, it is where I am not sure how useful it would be.

It negates the case for separate "utility" classes whose sole purpose is to house static methods that are all related to one particular interface.

Collections is always the example that springs to mind for me - if static methods were allowed on interfaces since the beginning, then this entire class wouldn't be necessary and the static methods could just belong to the Collection interface (which makes sense, because they all operate on Collection types.)

Of course, backwards compatibility means that we can't just do away with design like this in the API right away, but it means future library design can take it into consideration and hopefully produce slightly cleaner APIs because of it.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216