在java 1.8中的接口中添加静态方法 [英] Static methods added in interfaces in java 1.8

查看:807
本文介绍了在java 1.8中的接口中添加静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我们所知,在接口中允许使用java 1.8静态方法时,我看到了一些答案,如

但我不满意。
此外我认为这可能会导致以下问题:

As we know that in java 1.8 static methods are allowed in interfaces , I have seen some answers like static methods defined in interface from jdk 1 8 why did they need to do so
but I am not satisfied.
Furthermore I think it may cause problems like :

 public interface MyInterface{
      public static void myMethod();
    }

  class MyClass{
    MyInterface.myMethod();  // since myMethod is static but a huge error is waiting for us here ?
  }

但是我仍然认为有一种解决方法,因为这是添加<强大>由专业人士,所以任何人都可以解释 oracle如何解决这个问题,需要添加什么?

谢谢你。

But I still think there is a way out of this since this is added by professionals , so can anyone please explain how oracle solves this issue and what is the need to add this ?
Thank you in adavance.



我没有使用过java 1.8所以我从来不知道静态方法java 需要定义而不仅仅是声明,我一直认为接口是一个纯抽象类我认为这就是为什么定义一个方法的想法对我来说似乎很奇怪。谢谢您的帮助 ! 。


I have not used java 1.8 so I never knew that static methods in java needs to be defined not just declared , I always thought of the Interfaces as a Pure Abstract Class I think that's why the idea of defining a method seemed strange to me . Thank you for your help ! .

推荐答案

谈论需要添加什么静态方法:

Talking about "what is the need to add" static methods:

引自 http://www.informit.com/articles/article .aspx?p = 2191423


在Java 8之前,可以在
接口中声明静态方法,它通常的做法是将这些方法放在伴随的
实用程序类中。例如,java.util.Collections类是java.util.Collection接口的
伴侣,并声明静态
方法,这些方法在相关的Java
Collections Framework接口中更合适。您不再需要提供
自己的伴侣工具类。相反,你可以在适当的接口中放置静态方法
,这是一种培养的好习惯。

Before Java 8 made it possible to declare static methods in interfaces, it was common practice to place these methods in companion utility classes. For example, the java.util.Collections class is a companion to the java.util.Collection interface, and declares static methods that would be more appropriate in the relevant Java Collections Framework interfaces. You no longer need to provide your own companion utility classes. Instead, you can place static methods in the appropriate interfaces, which is a good habit to cultivate.

同样是静态方法in接口适用于提供实用程序方法,如空检查,集合排序等。重要的是,它通过拒绝实现类来覆盖它来提供安全性。

Also static methods in interfaces are good for providing utility methods like null check, collection sorting etc. And importantly it provides security by denying implementation classes from overriding it.

这篇关于在java 1.8中的接口中添加静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆