简体   繁体   中英

Why does java.awt.Color have two variables for every Color?

An excerpt from 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!!??
...

As you can see from the above extract, the Color white is assigned to two variables namely Color#WHITE and Color#white this is also the same case for:

 - 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)

Initially, I used to think that each color had two names for a reason. But when I checked the source code , I came to know that both of them have the same value !


I want to know why is there such a provision for having two variables for every color?

Is there any specific reason (be it historic, practical, etc.) for such usage?

And finally, which of the two to use in our applications? :

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

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

The variables were changed according to Java conventions which says constants to be uppercase only. The lowercase are still there for compatibility and have the same value.

To follow Java conventions you should always use the uppercase constants like:

Color.RED

Because they wanted to follow a convention(since JDK 1.4 ) which says constants should be used in uppercase only. So you should prefer to use:

Color.RED

If you see the source code of Color.java, you will find that both are same only.

public final static Color white     = new Color(255, 255, 255);

and Since 1.4

 public final static Color WHITE = white;

Just because of Java specification which says constant (final static) should be in upper case, a WHITE constant is introduced.

UPDATE:

By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM