Java中的接口是方法原型的规范。每当您需要指导程序员或订立合同以指定应如何使用类型的方法和字段时,都可以定义接口。
在Java 7中
从Java7开始,您只能将公共抽象作为接口方法的修饰符。interface MyInterface{
public abstract void display();
public abstract void setName(String name);
public abstract void setAge(int age);
}
将任何其他修饰符与接口方法一起使用将导致编译时错误。
从Java8
从Java8开始,接口允许使用默认方法和静态方法。静态方法-静态方法是使用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默认方法-默认方法是接口方法的默认实现,如果您在接口中有默认方法,则无需在已经实现此接口的类中实现它。
默认方法也称为防御者方法或虚拟扩展方法。您可以使用default关键字将默认方法定义为-default void display() {
System.out.println("This is a default method");
}
示例interface sampleInterface{
public void demo();
default void display() {
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements sampleInterface{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo();
obj.display();
}
}
输出结果This is the implementation of the demo method
This is a default method
从Java 9
从Java9开始,接口允许私有和私有静态方法。
示例interface MyInterface {
public abstract void demo();
public default void defaultMethod() {
privateMethod();
staticPrivateMethod();
System.out.println("This is a default method of the interface");
}
public static void staticMethod() {
staticPrivateMethod();
System.out.println("This is a static method of the interface");
}
private void privateMethod(){
System.out.println("This is a private method of the interface");
}
private static void staticPrivateMethod(){
System.out.println("This is a static private method of the interface");
}
}
public class InterfaceMethodsExample implements MyInterface {
public void demo() {
System.out.println("Implementation of the demo method");
}
public static void main(String[] args){
InterfaceMethodsExample obj = new InterfaceMethodsExample();
obj.defaultMethod();
obj.demo();
MyInterface.staticMethod();
}
}
输出结果This is a private method of the interface
This is a static private method of the interface
This is a default method of the interface
Implementation of the demo method
This is a static private method of the interface
This is a static method of the interface