gpt4 book ai didi

java - 为什么 java.awt.Color 对每种颜色都有两个变量?

转载 作者:行者123 更新时间:2023-11-29 09:43:47 25 4
gpt4 key购买 nike

摘自 java.awt.Color :

...
/**
* The color white. In the default sRGB space.
*/
public final static Color white = new Color(255, 255, 255);

/**
* The color white. In the default sRGB space.
* @since 1.4
*/
public final static Color WHITE = white; // My comment: THE SAME!!??
...

从上面的摘录中可以看出,Color white 被分配给两个 变量,即 Color#WHITEColor#white这也是同样的情况:

 - black     (and BLACK)
- blue (and BLUE)
- cyan (and CYAN)
- darkGray (and DARK_GRAY)
- gray (and GRAY)
- green (and GREEN)
- lightGray (and LIGHT_GRAY)
- magenta (and MAGENTA)
- orange (and ORANGE)
- pink (and PINK)
- red (and RED)
->white (and WHITE)<-discussed
- yellow (and YELLOW)

最初,我曾经认为每种颜色都有两个名字是有原因的。但是当我检查 source code , 我开始知道 它们都具有相同的值!


我想知道为什么要为每种颜色设置两个变量?

这种用法是否有任何特定原因(历史原因、实际原因等)?

最后,在我们的应用程序中使用哪两个?:

// THIS?:
Color newC = Color.white;

// OR THIS?:
Color newC = Color.WHITE;

最佳答案

变量根据 Java 约定进行了更改,Java 约定常量只能是大写。小写字母仍然存在以保持兼容性并具有相同的值。

要遵循 Java 约定,您应该始终使用大写常量,例如:

Color.RED

关于java - 为什么 java.awt.Color 对每种颜色都有两个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22708634/

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