What is the best way to implement constants in Java?

Asked 1 years ago, Updated 1 years ago, 117 views

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

I saw an example like this. Assuming that you can make a constant class with only a constant, you declared it a static final like that, but I hardly know Java, so I wonder if that's the best way.

java constant

2022-09-22 22:27

1 Answers

That's the best way. (public/private) static final TYPE NAME = VALUE; In this way, TYPE refers to the type of variable, and NAME usually consists of uppercase letters and _. For VALUE, you can put a constant value.

Note that a variable cannot change its value if it is declared final, but for an object it cannot point to another object. For example,

public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;

}

In this case, ORIGIN.x=3 works normally and the value of the point is (3,0).


2022-09-22 22:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.