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