각국 통화 화폐

정답예시에서 currency 생성자를 public으로 선언해주는 이유는 뭔가요?

CODE Link

  1. public class Main {
  2. public static void main(String[] args) {
  3. // 객체 생성
  4. KRW krw = new KRW(1500, "원");
  5. USD usd = new USD(100.50, "달러");
  6. EUR eur = new EUR(260.87, "유로");
  7. JPY jpy = new JPY(1400, "엔");
  8. // 부모 클래스를 통한 그룹화
  9. Currency[] currencies = { krw, usd, eur, jpy };
  10. // 모든 화폐정보를 출력
  11. for (Currency c : currencies) {
  12. System.out.println(c.toString());
  13. }
  14. }
  15. }
  16. /* 1. 부모 클래스 Currency를 만드시오. */
  17. /* 2. 상속을 통해 중복 코드를 제거 후, */
  18. /* 3. 생성자를 올바르게 수정하시오. */
  19. /* 4. toString() 메소드를 오버라이딩 하시오. */
  20. class Currency {
  21. protected double amount; // 수량(1000)
  22. protected String notation; // 표기법(원)
  23. Currency(double amount, String notation) {
  24. this.amount = amount;
  25. this.notation = notation;
  26. }
  27. public String toString() {
  28. return String.format("화폐 : 원");
  29. }
  30. }
  31. class KRW extends Currency {
  32. public KRW(double amount, String notation) {
  33. super(amount, notation);
  34. }
  35. public String toString() {
  36. return String.format("KRW: %.2f 원", super.amount);
  37. }
  38. }
  39. class USD extends Currency {
  40. public USD(double amount, String notation) {
  41. super(amount, notation);
  42. }
  43. public String toString() {
  44. return String.format("USD: %.2f 달러", super.amount);
  45. }
  46. }
  47. class EUR extends Currency {
  48. public EUR(double amount, String notation) {
  49. super(amount, notation);
  50. }
  51. public String toString() {
  52. return String.format("EUR: %.2f 유로", super.amount);
  53. }
  54. }
  55. class JPY extends Currency {
  56. public JPY(double amount, String notation) {
  57. super(amount, notation);
  58. }
  59. public String toString() {
  60. return String.format("JPY: %.2f 엔", super.amount);
  61. }
  62. }

INPUT

OUPUT

  1. KRW: 1500.00
  2. USD: 100.50 달러
  3. EUR: 260.87 유로
  4. JPY: 1400.00

생성자의 접근 제한자

큰 의미는 없습니다만, 생성자는 일반적으로 public을 사용합니다

PS.

질문 감사합니다!

[Markdown Preview]