19.オブジェクト指向を学ぼう 2(メソッド、コンストラクタ)
前回の「Processing:オブジェクト指向を学ぼう 1」では、Circleクラスを作って、そこに座標、大きさ、速度、色といったデータ(変数)を持たせるようにしました。
今回は、Circleクラスに円としての振る舞い(関数)を追加していきます。
1.クラスへの関数の追加
前回作ったプログラムは次のようになっていました。
class Circle{ float x; float y; float vy; float size; float gray;}
int n = 100;Circle[] c = new Circle[n];
void setup(){ noStroke(); size(1000,600); for(int i=0; i<n; i++){ c[i] = new Circle(); c[i].x = random(width); c[i].y = random(height); c[i].vy = random(1, 3); c[i].size = random(5, 40); c[i].gray = random(255); }}
void draw(){ background(255); for(int i=0; i<n; i++){ fill(c[i].gray); ellipse(c[i].x, c[i].y, c[i].size, c[i].size); c[i].y -= c[i].vy; }}
このプログラムでは、一つ一つの円のデータを参照して、表示したり、縦に動かしたりしています。
ですが、オブジェクト指向では、円が自分自身を表示して、自分を動かすというように、そのオブジェクトとしての振る舞いを作っていきます。そのために、Circleクラスに関数を作ります(この関数をメンバ関数やメソッドと呼ぶ)。
(基本的な関数の作り方はこちらを参考にしてください)
class Circle{ float x; float y; float vy; float size; float gray;
void display(){ fill(gray); ellipse(x, y, size, size); } void move(){ y -= vy; }}
Circleクラスの中にdisplay()とmove()が追加されました。これらの関数は、変数を参照する時と同じように、「.(ドット)」をつけて インスタンス.関数;
の形で呼び出します。
void draw(){ background(255); for(int i=0; i<n; i++){ c[i].display(); c[i].move(); }}
2.コンストラクタ
これまでは、setup()内でインスタンス化をしてからそれぞれのフィールドの値を決定していました。
c[i] = new Circle();c[i].x = random(width);c[i].y = random(height);c[i].vy = random(1, 3);c[i].size = random(5, 40);c[i].gray = random(255);
ですが、 new Circle();
をした時に実行される、インスタンスを初期化する関数を定義することができます。この関数のことを「 コンストラクタ 」と言います。
コンストラクタは次のように作ります。
class Circle{ float x; float y; float vy; float size; float gray;
///////////////コンストラクタ//////////////// Circle(){ x = random(width); y = random(height); vy = random(1, 3); size = random(5, 40); gray = random(255); }///////////////////////////////////////////////
void display(){ fill(gray); ellipse(x, y, size, size); } void move(){ y -= vy; }}
コンストラクタはクラス名と同じ名前の関数です。戻り値の型は指定しません。
コンストラクタには引数をつけることはできます。
Circle(float x1, float y1, float vy1, float size1, float gray1){ x = x1; y = y1; vy = vy1; size = size1; gray = gray1;}
これにより、インスタンス化をする時に、フィールドの初期値を指定することができるようになります。
Circle c = new Circle(100,200,3,30,150);
3.最終的に出来上がるコード全体
※コンストラクタに引数を追加していないものです。
class Circle{ float x; float y; float vy; float size; float gray;
Circle(){ x = random(width); y = random(height); vy = random(1, 3); size = random(5, 40); gray = random(255); }
void display(){ fill(gray); ellipse(x, y, size, size); } void move(){ y -= vy; }}
int n = 100;Circle[] c = new Circle[n];
void setup(){ noStroke(); size(1000,600); for(int i=0; i<n; i++){ c[i] = new Circle(); }}
void draw(){ background(255); for(int i=0; i<n; i++){ c[i].display(); c[i].move(); }}