Skip to content

Instantly share code, notes, and snippets.

@amippy
Created April 14, 2016 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amippy/9bc63bdf6d482480ee7b9b87be34cda5 to your computer and use it in GitHub Desktop.
Save amippy/9bc63bdf6d482480ee7b9b87be34cda5 to your computer and use it in GitHub Desktop.
筋トレ大好きな文系女学生のJava入門_静的メンバ ref: http://qiita.com/amippy/items/cc150d4b64aaf53ee730
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy mb1 = new MuscleBoy();
4 mb1.hp = 100;
5 MuscleBoy mb2 = new MuscleBoy();
6 mb2.hp = 70;
7 }
8 }
1 public class MuscleBoy{
2 int hp;
3 String name;
4 int money;
5 }
1 public class MuscleBoy{
2 int hp;
3 String name;
4 static int money;           //静的フィールド
5 }
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy mb1 = new MuscleBoy();
4 MuscleBoy mb2 = new MuscleBoy();
5 System.out.println(mb1.name);
6 System.out.println(MuscleBoy.money);
7 }
8 }
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy mb1 = new MuscleBoy();
4 MuscleBoy mb2 = new MuscleBoy();
5 MuscleBoy.money = 1000;
6 System.out.println(MuscleBoy.money); //1000と表示
7 System.out.println(mb1.money); //1000と表示
8 mb1.money = 2000;         //mb1に2000を代入
9 System.out.println(mb2.money); //mb2.moneyでも2000と表示
10 }
11 }
1 public class Main{
2 public static void main(String[] args){
3 //1人も筋肉ボーイを生み出していない状況
4 MuscleBoy.money = 1000;
5 System.out.println(MuscleBoy.money);
6 }
7}
1 public class MuscleBoy{
2 int hp;
3 String name;
4 static int money;
5
6 static void setRandomMoney(){ //staticをつけたメソッド
7 MuscleBoy.money = (int) (Math.random() * 1000);
8 }
9 }
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy.setRandomMoney();
4 System.out.println(MuscleBoy.money); //ランダムな金額が表示される
5 MuscleBoy mb1 = new MuscleBoy();
6 System.out.println(mb1.money); //同じ金額を表示
7 }
8 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment