練習問題 解答
4.6 練習問題 解答
問1
① ○
② ×:コンストラクタの名前は「クラス名と同じ」、戻り値は「設定できない」制約がある。
③ ×:コンストラクタにはアクセス修飾子をつけることができます。
④ ○
⑤ ×:クラス内にコンストラクタを定義してしまうと、デフォルトコンストラクタは呼び出されなくなる。
問2
① 戻り値の型が定義されている。
② 名前がクラス名と同じになっていない。
③ 引数の値の設定がフィールド変数に対して逆になっている。
1 | package jp.co.f1.basic.ch04exercise; |
2 |
3 | public class Books { |
4 | String title; |
5 | int price; |
6 |
7 | // コンストラクタ |
8 | public Books(String title, int price) { |
9 | this .title = title; |
10 | this .price = price; |
11 | System.out.println( "この本のタイトルを" + title + "、金額を" + price + "にしました。" ); |
12 | } |
13 | } |
問3
Score1.java1 | package jp.co.f1.basic.ch04exercise; |
2 |
3 | public class Score1 { |
4 | String name; // 名前 |
5 | int [] score = new int [ 5 ]; // 5教科の点数格納用配列 |
6 | int total; // 合計点 |
7 | double ave; // 平均点 |
8 |
9 | public Score1() { |
10 | // 名前を初期化 |
11 | this .name = null ; |
12 | // 繰り返し文を利用して配列を初期化 |
13 | for ( int i = 0 ; i < this .score.length; i++) { |
14 | this .score[i] = 0 ; |
15 | } |
16 | // 合計点を初期化 |
17 | this .total = 0 ; |
18 | // 平均点を初期化 |
19 | this .ave = 0.0 ; |
20 | } |
21 | } |
問4
Score2.java1 | package jp.co.f1.basic.ch04exercise; |
2 |
3 | public class Score2 { |
4 | String name; // 名前 |
5 | int [] score = new int [ 5 ]; // 5教科の点数格納用配列 |
6 | int total; // 合計点 |
7 | double ave; // 平均点 |
8 |
9 | public Score2(String name, int [] score, int total, double ave) { |
10 | // 引数の値で名前を設定 |
11 | this .name = name; |
12 |
13 | // 繰り返し文を利用して引数の値で配列を設定 |
14 | for ( int i = 0 ; i < this .score.length; i++) { |
15 | this .score[i] = score[i]; |
16 | } |
17 |
18 | // 引数の値で合計点を設定 |
19 | this .total = total; |
20 |
21 | // 引数の値で平均点を設定 |
22 | this .ave = ave; |
23 |
24 | } |
25 | } |