Created
June 7, 2012 17:56
-
-
Save editnuki/2890439 to your computer and use it in GitHub Desktop.
staticの有無によるメソッドの呼び出し方の違い
This file contains hidden or 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
public class Human { | |
public static int num; | |
public int age; | |
/* | |
* staticありの人数をカウントするメソッドを作成 | |
*/ | |
public static void humanNumber(){ | |
num++; | |
} | |
/* | |
* static無し年齢を取得するメソッドを作成 | |
*/ | |
// インスタンスフィールドのageの要素を戻り値としてインスタンスメソッドを呼ばれたらインスタンス毎の要素を返してやる | |
public int age() { | |
return this.age; | |
} | |
} |
This file contains hidden or 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
public class Main { | |
public static void main(String[] args) { | |
/* | |
* Human型のインスタンスを生成 Human型のインスタンスとは各自変数名を設定しているので | |
* インスタンスフィールドは各自別の要素を持つことができる 今までのたい焼きというのはHumanクラスが型となっていて | |
* 同じものを持つたい焼きがたくさんnewすることで生成可能 そして、中身がつぶあん、こしあんとか言っていたのは | |
* インスタンスフィールドの要素がインスタンスによって違うものを 持たせることが可能であるということ | |
* メンバがインスタンスによって異なる。メソッドの処理内容などは同じ。 | |
*/ | |
// ユーザの年齢を取得するためのmain部分.インスタンス生成後にクラスメソッドを実行する。 | |
Human suzuki = new Human(); | |
// インスタンス(個人)を生成した(生んだ)ら人間の数を増やす | |
Human.humanNumber(); | |
Human sato = new Human(); | |
Human.humanNumber(); | |
Human yamada = new Human(); | |
Human.humanNumber(); | |
/* | |
* インスタンス毎にインスタンスフィールドageに値を代入する | |
*/ | |
suzuki.age = 25; | |
yamada.age = 23; | |
sato.age = 22; | |
System.out.println("suzukiの年齢は" + suzuki.age() + "で、satoの年齢は" | |
+ sato.age() + "で、yamadaの年齢は" + yamada.age() + "です。"); | |
// ユーザの人数を取得するためのmain部分 | |
System.out.println("人間の人数は" + Human.num + "人です。"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment