Java接口中的默认方法与静态方法有何区别?
Java中的接口类似于类,但是它只包含抽象方法和声明为final和static的字段。
从Java 8开始,接口中引入了静态方法和默认方法。
默认方法 - 与其他抽象方法不同,这些方法可以有默认实现。如果接口中存在默认方法,则无需在已实现此接口的类中强制覆盖(提供方法体)。
简而言之,您可以使用实现类的对象访问接口的默认方法。
示例
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出
display method of MyInterface
静态方法 - 它们使用static关键字声明,并将与接口一起加载到内存中。您可以使用接口名称访问静态方法。
如果您的接口具有静态方法,则需要使用接口的名称来调用它,就像类的静态方法一样。
示例
在下面的示例中,我们在接口中定义了一个静态方法,并从实现该接口的类中访问它。
interface MyInterface{
public void demo();
public static void display() {
System.out.println("This is a static method");
}
}
public class InterfaceExample{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.demo();
MyInterface.display();
}
}输出
This is the implementation of the demo method This is a static method
静态方法和默认方法的区别:
调用方法
- 您可以使用接口的名称调用静态方法。
- 要调用默认方法,您需要使用实现类的对象。
覆盖方法
- 如果需要,您可以从实现类中覆盖接口的默认方法。
示例
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("display method of class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出
display method of class
- 您不能覆盖接口的静态方法;您只能使用接口的名称访问它们。如果您尝试通过在实现接口中定义类似的方法来覆盖接口的静态方法,则它将被视为类的另一个(静态)方法。
示例
interface MyInterface{
public static void display() {
System.out.println("Static method of the interface");
}
}
public class InterfaceExample{
public static void display() {
System.out.println("Static method of the class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
MyInterface.display();
InterfaceExample.display();
}
}输出
Static method of the interface Static method of the class
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP