練習問題 解答
6.5 練習問題 解答
問1
① ○
② ○
③ ×:クラスメンバはオブジェクト共通の情報なのでアクセスは可能です。
④ ×:クラスメンバはクラス自身に関連付けられるため、オブジェクトには関連付けられない。
⑤ ×:クラスメンバはクラスに実体として定義される。
問2
① クラスメソッドからインスタンス変数にアクセスしている。
② クラス変数に「this」キーワードをつけている。
③ 引数なしのコンストラクタが定義されていないのに、オブジェクト生成時に引数を与えていない。
④ 「オブジェクト名.クラスメソッド名」でクラスメソッドにアクセスしている。
※コンパイルエラーにはなりませんが、クラスメソッドにアクセスする場合は「クラス名.クラスメソッド名」と記述するのが一般的です。
問3
Book1.java
1 | package jp.co.f1.basic.ch06exercise; |
4 | private static int count = 0 ; |
10 | public Book1(String title, int price) { |
問4
Book2.java
1 | package jp.co.f1.basic.ch06exercise; |
4 | private static int count = 0 ; |
10 | public Book2(String title, int price) { |
18 | public void showBook() { |
19 | System.out.println( "この本のタイトルは" + this .title + "、価格は" + this .price |
21 | System.out.println( "生成番号は" + this .number + "です。" ); |
25 | public static int getCount() { |
問5
Practice0602.java
1 | package jp.co.f1.basic.ch06exercise; |
3 | import java.util.Scanner; |
6 | private static int count = 0 ; |
12 | public Book3(String title, int price) { |
20 | public void showBook() { |
21 | System.out.println( "この本のタイトルは" + this .title + "、価格は" + this .price |
23 | System.out.println( "生成番号は" + this .number + "です。" ); |
27 | public static int getCount() { |
32 | public class Practice0602 { |
33 | public static void main(String[] args) { |
35 | Scanner sin = new Scanner(System.in); |
38 | for ( int i = 0 ; i < 3 ; i++) { |
40 | System.out.print( "本のタイトルを入力してください->" ); |
41 | String title = sin.next(); |
44 | System.out.print( "本の価格を入力してください->" ); |
45 | int price = sin.nextInt(); |
48 | Book3 book = new Book3(title, price); |
58 | System.out.println( "■本の生成回数は「" + Book3.getCount() + "」回です。" ); |
解説
① new演算子を用いてScannerクラスをオブジェクト化します。
1 | Scanner sin = new Scanner(System.in); |
② for文を用いて3回ループさせます。
③ Scannerクラスnextメソッドを利用して文字列を入力し、変数titleに格納します。
1 | String title = sin.next(); |
④ ScannerクラスnextIntメソッドを利用して整数を入力し、変数priceに格納します。
1 | int price = sin.nextInt(); |
⑤ ③と④の値を引数にBook3オブジェクトを生成します。
1 | Book3 book = new Book3(title, price); |
⑥Book3オブジェクトのshowBookメソッドを呼び出し、書籍情報を画面に出力します。
⑦Book3のクラスメソッドであるgetCountメソッドを呼び出し、オブジェクト総生成回数を画面に出力します。
1 | System.out.println( "■本の生成回数は「" + Book3.getCount() + "」回です。" ); |
NEXT>> 7 パッケージとインポート