gpt4 book ai didi

Java 枚举静态最终实例变量

转载 作者:太空狗 更新时间:2023-10-29 22:59:34 27 4
gpt4 key购买 nike

万岁!

这段代码工作了一段时间,然后我决定添加一种默认颜色,然后它就停止工作了。我收到以下错误:

1 error found:
File: Status.java [line: 20]
Error: Status.java:20: illegal reference to static field from initializer

在编译时使用以下代码。

import java.awt.Color;

enum Status
{
OFF ("Off"),
TRAINING ("Training", new Color(255, 191, 128)),
BEGINNER ("Beginner", new Color(128, 255, 138)),
INTERMEDIATE ("Intermediate", new Color(128, 212, 255)),
ADVANCED ("Advanced", new Color(255, 128, 128));

public final String name;
public final Color color;

public static final Color defaultColor = Color.WHITE;

Status(String name)
{
this(name, defaultColor);
}
Status(String name, Color color)
{
this.name = name;
this.color = color;
}
}

据我所知,这应该可以工作,但无论出于何种原因,Java 决定抛出一个错误。有什么想法吗?

最佳答案

defaultColor 只会在调用构造函数后 进行初始化 - 因此在此之前它将具有默认值 (null)。一种选择是将默认颜色放入嵌套类型中:

import java.awt.Color;

enum Status
{
OFF ("Off"),
TRAINING ("Training", new Color(255, 191, 128)),
BEGINNER ("Beginner", new Color(128, 255, 138)),
INTERMEDIATE ("Intermediate", new Color(128, 212, 255)),
ADVANCED ("Advanced", new Color(255, 128, 128));

public final String name;
public final Color color;

Status(String name)
{
this(name, Defaults.COLOR);
}
Status(String name, Color color)
{
this.name = name;
this.color = color;
}

private static class Defaults
{
private static Color COLOR = Color.WHITE;
}
}

当然,如果您只在代码中引用默认颜色一次,您不妨在构造函数调用中对其进行硬编码:

Status(String name)
{
this(name, Color.WHITE);
}

关于Java 枚举静态最终实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435267/

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