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