Created
July 24, 2010 13:15
-
-
Save johobemax/488687 to your computer and use it in GitHub Desktop.
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
/** | |
* static変数・メソッドのサンプル | |
* staticを付けると、クラス全体が共有する変数・メソッドになる。 | |
*/ | |
class ClassMate | |
{ | |
//static変数…クラス共有の変数 | |
static String master; //担任の名前 | |
//インスタンス変数…オブジェクトごとに作られる変数 | |
String name; //学生の名前 | |
/** | |
* @param name 学生の名前 | |
*/ | |
ClassMate(String name) | |
{ | |
this.name = name; | |
} | |
//staticメソッド…クラス共有のメソッド | |
/** | |
* 担任を表示する | |
*/ | |
static void showMaster() | |
{ | |
System.out.println("class's master is " + master); | |
} | |
/** | |
* 担任を変更するメソッド | |
* @param name 新しい担任の名前 | |
*/ | |
static void setMaster(String name) | |
{ | |
master = name; | |
} | |
} | |
class StaticTest | |
{ | |
public static void main(String[] args) | |
{ | |
ClassMate.master = "Horikawa"; | |
// static変数は、インスタンス化しなくても参照できる | |
System.out.println("class's master is " + ClassMate.master); | |
ClassMate m1 = new ClassMate("Yamada"); | |
ClassMate m2 = new ClassMate("Uchida"); | |
//インスタンスからも参照できる | |
System.out.println(m1.name + "'s master is " + m1.master); | |
System.out.println(m2.name + "'s master is " + m2.master); | |
m1.master = "Kochi"; //Yamadaの担任をKochiに変更すると | |
System.out.println("class's master is " + ClassMate.master); | |
System.out.println(m1.name + "'s master is " + m1.master); | |
System.out.println(m2.name + "'s master is " + m2.master); | |
// クラスみんなの担任が変更になる。共有してるからね。 | |
//staticメソッドを使ってみる | |
ClassMate.setMaster("Matsushima"); | |
ClassMate.showMaster(); | |
m1.showMaster(); | |
m2.showMaster(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment