Java接口字段_如何在Java中访问接口的字段?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值