Java – sharing constants in multiple classes (Android Minesweeper)
I'm using the extended button to create an instance of a class and directly access integer variables for better performance. I'm using constants to easily identify the current settings of variables
I have constant declarations and instantiate them in the button class and activity class. I found a similar problem, and it's not good to create a class just to keep constants
What is the best way to use the same constant declaration in both classes?
I'm a beginner programmer, so I probably ignored a simple solution
Button class:
public class GridButton extends Button {
public int displayStatus;
// constants for mine display status
private static final int UNTOUCHED = 1;
private static final int UNCOVERED = 2;
private static final int FLAGGED = 3;
private static final int HIT = 4;
...
}
Activity class:
public class PlayGameActivity extends Activity {
private GridButton[][] gridButtons;
// constants for mine display status
private static final int UNTOUCHED = 1;
private static final int UNCOVERED = 2;
private static final int FLAGGED = 3;
private static final int HIT = 4;
...
// e.g. accessing displayStatus value
if (gridButtons[currentRow][currentColumn].displayStatus == FLAGGED)
{
}
}
resolvent:
To share content, you can create constants in separate classes and access them statically
class Constants {
public static final int UNTOUCHED = 1;
}
Then in these two courses, you can go to constants. Untouched
In this case, I will avoid using magic numbers and replace them with enum
enum DisplayStatus {
Untouched, Uncovered, Flagged, Hit
}
And replace all int displaystatus with displaystatus displaystatus. Now you and other readers have a clear understanding of what int represents
Ideally, you always want to use a specific type to limit the range of possible values. In your example, only the numbers 1-4 are valid, but your type is as wide as int, so it can be any value (such as - 1 or 23543)
Good luck!