gpt4 book ai didi

java - 对接口(interface)的空引用如何返回值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:27 25 4
gpt4 key购买 nike

代码是:

interface I {
int i = 0;
void display();
}

class A implements I {
I i1;

public static void main(String[] args) {
A a = new A();
a.display();
}

public void display() {
System.out.println(i1); //1
System.out.println(i1.i); //2
}
}

代码的输出是

null
0

但是当i的地址为null时,那么在第二个i1.i中它是如何返回一个值的呢?如何使用空引用指向变量?

最佳答案

Fields declared in interfaces are implicitly static.

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

这个

i1.i

是一个static 字段访问表达式。它依赖于 i1 的类型,而不是它的值。它完全等同于

I.i // where I is the name of your interface

关于java - 对接口(interface)的空引用如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com