Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static and default methods are added to interfaces in Java?

Tags:

java

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.

like image 715
Tarik Avatar asked Mar 15 '26 21:03

Tarik


1 Answers

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.

like image 190
Michael Berry Avatar answered Mar 19 '26 15:03

Michael Berry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!