Java中的接口是方法原型的规范。每当您需要指导程序员或订立合同以指定应如何使用类型的方法和字段时,都可以定义接口。默认,接口的所有成员(方法和字段)都是public。
接口中的所有方法都是公共的和抽象的(静态和默认方法除外)。
接口的所有字段默认都是public,static和final。
如果声明/定义字段时未使用public,static或final或所有三个修饰符。Java编译器代表您放置它们。
示例
在下面的Java程序中,我们将提交一个没有public或static或final修饰符的文件。public interface MyInterface{
int num =40;
void demo();
}
如果您使用javac命令进行编译,如下所示-c:\Examples>javac MyInterface.java
它被编译而没有错误。但是,如果您使用javap命令在编译后验证了接口,如下所示-c:\Examples>javap MyInterface
Compiled from "MyInterface.java"
public interface MyInterface {
public static final int num;
public abstract void demo();
}
访问接口的字段
通常,要创建接口类型的对象,您需要实现它并为其中的所有抽象方法提供实现。这样做时,接口的所有字段都由实现类继承,即,接口的字段的副本在实现它的类中可用。
由于默认情况下接口的所有字段都是静态的,因此您可以使用接口名称访问它们-
示例interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public static int num = 10000;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
System.out.println("Value of num of the interface "+MyInterface.num);
System.out.println("Value of num of the class "+obj.num);
}
}
输出结果Value of num of the interface 100
Value of num of the class 10000
但是,由于接口的变量是最终变量,因此无法将值重新分配给它们。如果尝试这样做,将生成编译时错误。
示例interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public static int num = 10000;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
MyInterface.num = 200;
}
}
输出结果
编译时错误InterfaceExample.java:14: error: cannot assign a value to final variable num
MyInterface.num = 200;
^
1 error