Importance of constant class
If I put constant variable values directly in classes, its panic when this value get changes. If i make a constant class to keep such constants it helps to do changes in one class on开发者_StackOverflow中文版ly. But again I need to identify all the classes which are using these constants. Because recompilation is required.
then what is the need of separate constant class? suggest me another way to manage constants, if better.
Use property file instead of making constant class
I would NEVER use a class for all of my constants.
I would also NEVER use a class for all my integers, or for all strings, or one class for all final variables and another class for all static variables, etc.
Group your members by function, not by a language feature.
If i make a constant class to keep such constants it helps to do changes in one class only.
Following that logic, you could put your whole project in a single class.
I'm pretty new to JAVA and not sure to understand your question very well, but what about something like a file Points.java (for the example, but you can make this for Strings, int, Objects... or any types) where you have :
package classes;
import java.awt.Point;
public enum Points {
FIRST_POSITION(0,50,50),SECOND_POSITION(1,150,200),THIRD_POSITION(2,175,200),FOURTH_POSITION(3,175,200);
private int index;
private Point point;
private Points(int index,int x, int y){
this.index = index;
this.point = new Point(x, y);
}
public int getIndex() {
return index;
}
public Point getPoint() {
return point;
}
}
You may use multiple constructors for different properties (but I'm not sure that this last possibility could be a good technique since certain getters may differ in names...) And you can retrieve values everywhere like :
System.out.println(Points.FIRST_POSITION + ", index[" + Points.FIRST_POSITION.getIndex() + "]" + ", position:" + Points.FIRST_POSITION.getPoint());
System.out.println(Points.SECOND_POSITION + ", index[" + Points.SECOND_POSITION.getIndex() + "]" + ", position:" + Points.SECOND_POSITION.getPoint());
System.out.println(Points.THIRD_POSITION + ", index[" + Points.THIRD_POSITION.getIndex() + "]" + ", position:" + Points.THIRD_POSITION.getPoint());
System.out.println(Points.FOURTH_POSITION + ", index[" + Points.FOURTH_POSITION.getIndex() + "]" + ", position:" + Points.FOURTH_POSITION.getPoint());
精彩评论