回答編集履歴

2

コード追加

2022/08/12 08:20

投稿

jimbe
jimbe

スコア12646

test CHANGED
@@ -1,2 +1,97 @@
1
1
  enum は new でオブジェクトを生成することは出来ません。enum 内で宣言しているモノのみしか使えないからこそ enum の意味があります。
2
2
  また、 enum で定義されていないメソッドは当然使えません。
3
+
4
+ ---
5
+ test1/Bond.java
6
+ ```java
7
+ package test1;
8
+
9
+ import java.util.Objects;
10
+
11
+ public class Bond {
12
+ private String code;
13
+ private String name;
14
+ private int maturity;
15
+ private double coupon;
16
+ private BondType type;
17
+
18
+ public Bond (String code, String name, int maturity, double coupon) {
19
+ if (code == null || name == null) {
20
+ throw new IllegalArgumentException("nullです。");
21
+ }
22
+ if (maturity < 20000101 || 29991231 < maturity || coupon < 0) {
23
+ throw new IllegalArgumentException("数値が範囲外です");
24
+ }
25
+
26
+ this.code = code;
27
+ this.name = name;
28
+ this.maturity = maturity;
29
+ this.coupon = coupon;
30
+ if (coupon == 0) {
31
+ type = BondType.ZERO_COUPON_BOND;
32
+ } else {
33
+ type = BondType.COUPON_BOND;
34
+ }
35
+ }
36
+ public String getCode() {
37
+ return this.code;
38
+ }
39
+ public String getName() {
40
+ return this.name;
41
+ }
42
+ public int getMaturity() {
43
+ return this.maturity;
44
+ }
45
+ public double getCoupon() {
46
+ return this.coupon;
47
+ }
48
+ public BondType getBondType() {
49
+ return this.type;
50
+ }
51
+
52
+ //以下は Eclipse により自動生成
53
+ @Override
54
+ public String toString() {
55
+ return "Bond [code=" + code + ", name=" + name + ", maturity=" + maturity + ", coupon=" + coupon + ", type="
56
+ + type + "]";
57
+ }
58
+ @Override
59
+ public int hashCode() {
60
+ return Objects.hash(code, coupon, maturity, name, type);
61
+ }
62
+ @Override
63
+ public boolean equals(Object obj) {
64
+ if (this == obj) return true;
65
+ if (obj == null) return false;
66
+ if (getClass() != obj.getClass()) return false;
67
+ Bond other = (Bond) obj;
68
+ return Objects.equals(code, other.code) && Double.doubleToLongBits(coupon) == Double.doubleToLongBits(other.coupon)
69
+ && maturity == other.maturity && Objects.equals(name, other.name) && type == other.type;
70
+ }
71
+ }
72
+ ```
73
+ test1/BondType.java
74
+ ```java
75
+ package test1;
76
+
77
+ public enum BondType {
78
+ COUPON_BOND, ZERO_COUPON_BOND
79
+ };
80
+ ```
81
+ test2/BondTest.java
82
+ ```java
83
+ package test2;
84
+
85
+ import test1.Bond;
86
+
87
+ public class BondTest {
88
+ public static void main (String [] args) {
89
+ Bond bond3 = new Bond("code", "name", 20220812, 1.0);
90
+ System.out.println(bond3.getBondType());
91
+ }
92
+ }
93
+ ```
94
+ 実行結果
95
+ ```plain
96
+ COUPON_BOND
97
+ ```

1

追加

2022/08/12 08:13

投稿

jimbe
jimbe

スコア12646

test CHANGED
@@ -1 +1,2 @@
1
1
  enum は new でオブジェクトを生成することは出来ません。enum 内で宣言しているモノのみしか使えないからこそ enum の意味があります。
2
+ また、 enum で定義されていないメソッドは当然使えません。