接口中静态和默认方法的区别 [英] Difference Between static and default methods in interface
问题描述
当我注意到你现在可以在界面中定义静态和默认方法时,我正在通过接口学习。
I was learning through interfaces when I noticed that you can now define static and default methods in an interface.
public interface interfacesample2 {
public static void method() {
System.out.println("hello world");
}
public default void menthod3() {
System.out.println("default print");
}
}
请解释两者的区别以及是否有我们何时使用它的例子会很好。在接口上有点困惑。
Kindly explain the difference of the two and also if there's an example of when we would use this would be nice. A little confused on Interfaces.
推荐答案
Java 8中的静态和默认方法之间的差异:
Differences between static and default methods in Java 8:
1)默认方法可以覆盖实现类,而静态不能。
1) Default methods can be overriden in implementing class, while static cannot.
2)静态方法属于仅到Interface类,因此您只能在Interface类上调用静态方法,而不是在实现此接口的类上调用,请参阅:
2) Static method belongs only to Interface class, so you can only invoke static method on Interface class, not on class implementing this Interface, see:
public interface MyInterface {
default void defaultMethod(){
System.out.println("Default");
}
static void staticMethod(){
System.out.println("Static");
}
}
public class MyClass implements MyInterface {
public static void main(String[] args) {
MyClass.staticMethod(); //not valid - static method may be invoked on containing interface class only
MyInterface.staticMethod(); //valid
}
}
3)类和接口可以有具有相同名称的静态方法,并且都不会覆盖其他方法!
3) Both class and interface can have static methods with same names, and neither overrides other!
public class MyClass implements MyInterface {
public static void main(String[] args) {
//both are valid and have different behaviour
MyClass.staticMethod();
MyInterface.staticMethod();
}
static void staticMethod(){
System.out.println("another static..");
}
}
这篇关于接口中静态和默认方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!