如何在Java中访问接口的字段?
Java中的接口是方法原型的规范。无论何时您需要指导程序员或制定一个合同,指定某个类型的字段和方法应该如何,您都可以定义一个接口。默认情况下,
所有成员(方法和字段)都是公共的。
接口中的所有方法都是公共的且抽象的(静态和默认方法除外)。
接口的所有字段默认情况下都是公共的、静态的和最终的。
如果您声明/定义字段时没有使用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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP