Java中的接口类似于类,但是它只包含final和static的抽象方法和字段。
由于Java8在接口中引入了静态方法和默认方法。
默认方法-与其他抽象方法不同,这些是可以具有默认实现的方法。如果接口中有默认方法,则在已实现此接口的类中重写(提供正文)不是强制性的。
简而言之,您可以使用实现类的对象来访问接口的默认方法。
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("Default implementation of the display method");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出结果
Default implementation of the display method
强制覆盖接口的默认方法不是强制性的,但是仍然可以像超类的常规方法一样覆盖它们。但是,请确保删除默认关键字。
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("Default implementation of the display method");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("Hello welcome to Nhooo");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}输出结果
Hello welcome to Nhooo