如何访问 Java 中接口的字段?
object oriented programmingprogramming
Java 中的接口是方法原型的规范。每当您需要指导程序员或制定合同以指定类型的方法和字段应如何时,您都可以定义一个接口。默认情况下,
接口的所有成员(方法和字段)都是public。
接口中的所有方法都是public和abstract(静态和默认除外)。
默认情况下,接口的所有字段都是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
但是,由于接口的变量是 final,因此您无法为它们重新赋值。如果您尝试这样做,将会产生编译时错误。
示例
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