1 2 3 4 5 6 7 8 9 10 11 | package ex14_02_1; public class Exec { public static void main(String[] args) { Dice dice1 = new Dice( 6 , "黒" ); Dice dice2 = new Dice( "赤" ); Dice dice3 = new Dice(); System.out.println( "dice1=" + dice1.val+ "/" +dice1.color); System.out.println( "dice2=" + dice2.val+ "/" +dice2.color); System.out.println( "dice3=" + dice3.val+ "/" +dice3.color); } } |
コンストラクタが設定する初期値に注意する。引数が1つのコンストラクタは目数を1にし、引数がないコンストラクタは、目数は1、色は白に初期化する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package ex14_02_2; public class Card { String suit; // カードの種類 "スペード"、"ハート"、"クラブ"、"ダイヤ" int number; // カードの札番号 1~13 public Card(String suit, int number) { this .suit = suit; this .number = number; } public Card(String suit) { // numberは常に1とする this (suit, 1 ); } public Card( int number) { // suitは常に"スペード"とする this ( "スペード" , number); } public Card() { // <問2> 引数のないコンストラクタ } public String face() { // カードを表す文字列を返す return suit + "/" + number; } } |