简体   繁体   English

为什么在Java中的接口中添加了静态和默认方法?

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

I use Java but I have a better background with C#. 我使用Java,但我有更好的C#背景。 I've been reading Java's default and static methods in interfaces. 我一直在阅读接口中Java的defaultstatic方法。 I think I understood how default methods in interfaces would be useful. 我想我理解接口中的默认方法是如何有用的。 For instance, we have extension methods in C#. 例如,我们在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 . 它帮助语言设计者的一件事是他们可以自由地为诸如WhereSelect等接口添加新方法,其中lambda表达式可以在不破坏二进制代码兼容性的情况下使用 So default methods in Java's interfaces can help in the same way. 因此,Java接口中的default方法可以以相同的方式提供帮助。

But when it comes to static methods in Java interfaces, it is where I am not sure how useful it would be. 但是当谈到Java接口中的static方法时,我不确定它有多么有用。 Can anyone explain me why static methods added to interfaces and in what cases they are useful for us developers. 任何人都可以解释为什么static方法添加到接口以及在什么情况下它们对我们的开发人员有用。 I also would like to hear if there are different reasons for default method other than what I mentioned. 我还想知道除了我提到的以外, default方法是否有不同的原因。

But when it comes to static methods in Java interfaces, it is where I am not sure how useful it would be. 但是当谈到Java接口中的静态方法时,我不确定它有多么有用。

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.) Collections总是让我想到的例子 - 如果从一开始就允许在接口上使用静态方法,那么整个类就没有必要了,静态方法可能只属于Collection接口(这是有意义的,因为它们所有操作都在Collection类型上。)

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. 当然,向后兼容性意味着我们不能立即在API中取消这样的设计,但这意味着未来的库设计可以将其考虑在内,并希望因此产生稍微清洁的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM