Skip to content

Instantly share code, notes, and snippets.

@amippy
Created April 9, 2016 16:00
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/cec28c7cee079943f146542b44d00b92 to your computer and use it in GitHub Desktop.
Save amippy/cec28c7cee079943f146542b44d00b92 to your computer and use it in GitHub Desktop.
筋トレ大好きな文系女学生のJava入門_コンストラクタ ref: http://qiita.com/amippy/items/ea83523e7ea72514518c
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy mb = new MuscleBoy(); //インスタンスを生成
4 mb.name = "ホエイ";           //初期値セット
5 mb.hp = 100; //初期値セット
6 MuscleGirl mg = new MuscleGirl(); //またインスタンスを生成
7 mg.name = "アミノ"; //また初期値
8 mg.hp = 100; //また初期値
9 Protein p = new Protein(); //インスタンスを生成
10 p.name = "プロテイン"; //初期値
11 p.recover(mb);             //やっとメインプログラム
12 p.recover(mg);
13 }
14}
フィールドの初期値
int型,short型,long型等の数値の型 ------> 0    
char型(文字)---------------------------> ¥u0000
boolean型-----------------------------> false
int[]型-------------------------------> null
String型------------------------------> null
1 public class MuscleBoy{
2 int hp;
3 String name;
4
5 void run(){
6 System.out.println(this.name + "は走っている");
7 }
8 MuscleBoy(){
9 this.hp = 100; //hpフィールドを100で初期化
10 }
11}
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy mb = new MuscleBoy();
4
5 System.out.println(mb.hp);   //すでにhpには100が代入されているため、画面に「100」と表示
6 }
7}
コンストラクタの基本
1 public class クラス名{
2 クラス名(){
3 //ここに自動実行処理を記述
4 }
5}
1 public class MuscleBoy{
2 int hp;
3 String name;
4
5 MuscleBoy(String name){ //引数として文字列を1つ受け取る
6 this.hp = 100;
7 this.name = name;
8 }
9}
1 public class Main{
2 public static void main(String[] args){
3 MuscleBoy mb = new MuscleBoy("ホエイ"); //コンストラクタに「ホエイ」が渡される
4
5 System.out.println(mb.hp); //100と表示
6 SYstem.out.println(mb.name);  //ホエイと表示
7 }
8}
1 public class MuscleBoy{
2 int hp;
3 String name;
4
5 MuscleBoy(String name){  //以前からあったコンストラクタ1
6 this.hp = 100;
7 this.name = name;
8 }
9 MuscleBoy(){       //新しく作ったコンストラクタ2
10 this("Nothing");
11
12 }
13}
1 public class Main{
2 pubic static void main(String[] args){
3 MuscleBoy mb1 = new MuscleBoy("ホエイ"); //文字列引数があるためコンストラクタ1が呼び出される
4
5 System.out.println(mb.name); //画面に「ホエイ」と表示
6 MuscleBoy mb2 = new MuscleBoy();  //引数がないのでコンストラクタ2が呼び出される
7
8 System.out.println(mb2.name); //画面に「Nothing」と表示
9 }
10}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment