This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/6…

Issue an overview

I’ve seen examples like this:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}
Copy the code

And suppose I can have a Constants class to wrap Constants and declare them static final.

I know almost nothing about Java and wonder if this is the best way to create constants.

Best answer

This is perfectly acceptable, maybe even standard

(public/private) static final TYPE NAME = VALUE;
Copy the code

Where TYPE is the TYPE, NAME is the NAME of all uppercase letters with underlined Spaces, and VALUE is a constant VALUE.

I strongly recommend not putting constants in your own classes or interfaces.

Caveat: Variables declared final and mutable can still be changed; However, variables can never point to other objects. Such as:

public static final Point ORIGIN = new Point(0.0);

public static void main(String[] args){

    ORIGIN.x = 3;

}
Copy the code

That’s legal, so ORIGIN is going to be a point at 3 comma 0.

Other answer

I strongly recommend against using a single constant class. This seemed like a good idea at the time, but when developers refused to log constants and the class grew to contain up to 500 constants that were unrelated to each other (completely different aspects of the application), it often turned into completely unreadable constant files. Instead of:

If you have access to Java 5+, use enumerations to define specific constants for your application area. For these constants, all parts of the application area should refer to enumerations, not constants. You can declare enumerations similar to declaring classes. Enumerations are probably the most (and only) useful feature of Java 5+.