I have two ways to define constants. First one holds the bunch of static final DataType variables in a class and another by using Enum.
Here is the fist type:
public class TipTipProperties {
public static final String MAX_WIDTH_AUTO = "auto";
public static final String POSITION_RIGHT = "right";
}
And the usage of these variable will via static call, as an example: TipTipProperties.MAX_WIDTH_AUTO
And the second type is:
public enum TipTipProperties {
MAX_WIDTH_AUTO(MaxWidth.AUTO),
POSITION_RIGHT(Position.RIGHT);
private MaxWidth maxWidth;
private Position position;
private TipTipProperties(MaxWidth maxWidth) {
this.maxWidth = maxWidth;
}
private TipTipProperties(Position position) {
this.position = position;
}
public MaxWidth getMaxWidth() {
return maxWidth;
}
public Position getPosition() {
return position;
}
public enum MaxWidth {
AUTO("auto");
private String width;
private MaxWidth(String width) {
this.width = width;
}
public String getWidth() {
return width;
}
}
public enum Position {
RIGHT("right"),
private String position;
private Position(String position) {
this.position = position;
}
public String getPosition() {
return position;
}
}
}
As an example usage: TipTipProperties.POSITION_RIGHT.getPosition().getPosition()
.
My question is:
Thanks in advance.
A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
In C/C++ program we can define constants in two ways as shown below: Using #define preprocessor directive. Using a const keyword.
In mathematics, a constant is a specific number or a symbol that is assigned a fixed value. In other words, a constant is a value or number that never changes in expression. Its value is constantly the same. Examples of constant are 2, 5, 0, -3, -7, 2/7, 7/9 etc.
Enum is the best to do this as Joshua Bloch said in Effective Java,you will have more control using Enum like if you want to print all constants,you can. with class constants you can not have type safety.read this for further help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With