Static methods added in interfaces in java 1.8 [closed]

南笙酒味 提交于 2019-12-04 14:52:17

问题


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 ?
  }

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.


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 ! .

回答1:


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

Quoting from http://www.informit.com/articles/article.aspx?p=2191423

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.

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.




回答2:


There's no problem here, the static method is owned by class, not it's members, so the only error here is the fact you didn't defined the method itselt (just declared it, which is not allowed with static methods).



来源:https://stackoverflow.com/questions/25934134/static-methods-added-in-interfaces-in-java-1-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!