gpt4 book ai didi

java - 意外行为 - java 是否在此处执行编译时优化?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:56 24 4
gpt4 key购买 nike

请看这段代码:

class Ideone
{
static int value = 3;

Ideone getIdeone()
{
System.out.println("getIdeone() called");
return null;
}

public static void main (String[] args) throws java.lang.Exception
{
Ideone ideone = new Ideone();
System.out.println(ideone.getIdeone().value);
}
}

输出:

getIdeone() called

3

Ideone 链接 here

您一定已经观察到,我正在调用 getIdeone(),它返回 null,然后从 null 对象中获取 value

这是怎么回事?编译器是否执行一些编译时优化并直接从类中获取 value,原因是它是静态的?

最佳答案

因为 value 是一个 static 字段,您不需要实例来访问它,所以 null 就足够了。它确实是直接从类中获取的。

编译器已经警告过你:

The static field Ideone.value should be accessed in a static way


作为额外练习,看看当涉及子类时会发生什么。底部的代码将提供以下输出:

getIdeone() in Test called

3

(所以 不是 5),即使(在运行时)getIdeone() 预计返回一个测试。这是因为编译器已经将其转换为对 Ideone 的静态字段的调用 - 运行时发生什么并不重要。

public class Ideone {
static final int value = 3;

Ideone getIdeone() {
System.out.println("getIdeone() called");
return null;
}

public static void main(String[] args) throws java.lang.Exception {
Ideone ideone = new Ideone().new Test();
System.out.println(ideone.getIdeone().value);
}

class Test extends Ideone {
static final int value = 5;

@Override
Test getIdeone() {
System.out.println("getIdeone() in Test called");
return null;
}
}
}

关于java - 意外行为 - java 是否在此处执行编译时优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31771260/

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