Last active
December 2, 2016 04:45
-
-
Save kdmgs110/ad227fd6a6e0c1826ec0ec6c2eef9258 to your computer and use it in GitHub Desktop.
コンストラクタの設定 CHAPTER 14
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************Dice.java********************* */ | |
package pass01; | |
/******************Dice.java********************* */ | |
package pass01; | |
public class Dice { //Diceクラス | |
int val;//フィールド変数 | |
//コンストラクタの設定 | |
public Dice(int val){ // numは初期値に設定したい値 | |
this.val = val; //このオブジェクトのval = val | |
} | |
public void play(){ | |
val = (int)(Math.random()*6)+1; //1~6のどれかを代入する | |
} //インスタンスメソッド | |
} | |
/******************Exec.java********************* */ | |
package pass01; | |
/* | |
* オブジェクト指向P304 | |
* new演算子 | |
* newで作成したオブジェクト=インスタンス、設計図クラスから作成された個々のオブジェクト | |
*/ | |
public class Exec { | |
public static void main(String[] args) { | |
Dice dice = new Dice(1); //valの初期値を1にする | |
System.out.println("目数"+dice.val); //valをコンソールに表示する。 | |
dice.play(); //diceの目数を変更する | |
System.out.println("目数=" + dice.val); | |
} | |
} | |
/*出力 | |
目数1 //コンストラクタで自動設定 | |
目数=3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment