0
저는 Java How to Program 10 판을 읽고 처음 몇 장을 읽었습니다. 이 예제에서 우리는 SecureRandom 클래스를 확인하는 방법을 보여 주지만 완전히 저를 괴롭히는 부분이 있습니다. 이 책에서 왜 객체 참조 변수 static final을 선언 하시겠습니까?
// Fig. 6.8: Craps.java
// Craps class simulates the dice game craps.
import java.security.SecureRandom;
public class Craps
{
// create secure random number generator for use in method rollDice
private static final SecureRandom randomNumbers = new SecureRandom();
// enum type with constants that represent the game status
private enum Status { CONTINUE, WON, LOST };
// constants that represent common rolls of the dice
private static final int SNAKE_EYES = 2;
private static final int TREY = 3;
private static final int SEVEN = 7;
private static final int YO_LEVEN = 11;
private static final int BOX_CARS = 12;
// plays one game of craps
public static void main(String[] args)
{
int myPoint = 0; // point if no win or loss on first roll
Status gameStatus; // can contain CONTINUE, WON or LOST
int sumOfDice = rollDice(); // first roll of the dice
// determine game status and point based on first roll
switch (sumOfDice)
{
case SEVEN: // win with 7 on first roll
case YO_LEVEN: // win with 11 on first roll
gameStatus = Status.WON;
break;
case SNAKE_EYES: // lose with 2 on first roll
case TREY: // lose with 3 on first roll
case BOX_CARS: // lose with 12 on first roll
gameStatus = Status.LOST;
break;
default:
gameStatus = Status.CONTINUE; // game is not over
myPoint = sumOfDice; // remember the point
System.out.printf("Point is %d%n", myPoint);
break;
}
// while game is not complete
while (gameStatus == Status.CONTINUE) // not WON or LOST
{
sumOfDice = rollDice(); // roll dice again
// determine game status
if (sumOfDice == myPoint) // win by making point
gameStatus = Status.WON;
else if (sumOfDice == SEVEN) // lose by rolling 7 before point
gameStatus = Status.LOST;
}
// display won or lost message
if (gameStatus == Status.WON)
System.out.println("Player wins");
else
System.out.println("Player loses");
}
// roll dice, calculate sum and display results
public static int rollDice()
{
// pick random die values
int die1 = 1 + randomNumbers.nextInt(6); // first die roll
int die2 = 1 + randomNumbers.nextInt(6); // second die roll
int sum = die1 + die2; // sum of die values
// display results of this roll
System.out.printf("Player rolled %d + %d = %d%n", die1, die2, sum);
return sum;
}
} // end class Craps
, 그것은이 클래스의 개인 정적 최종 변수로 선언 된 것을 언급
SecureRandom
그래서 하나의 객체가 항상
rollDice()
, 메소드를 호출하는 데 사용되는 것이다.
Craps
클래스의 다중 인스턴스를 포함하는 프로그램이있는 경우 모두이 하나의 객체를 공유합니다. 제 질문은 클래스
SecureRandom
의 여러 인스턴스가 필요할 기회가 올 것입니까? 다음 질문은
SecureRandom
이라는 객체 참조 변수이므로
Craps
의 변수로 계속 호출되는 이유는 무엇입니까?