コンテンツにスキップ

20.オブジェクト指向を学ぼう 3(継承)

1.継承とは

オブジェクト指向プログラミングにおいて、あるクラスが既存の別のクラスの性質を受け継いでいること。

2.Triangleクラスの作成

前回の「Processing:オブジェクト指向を学ぼう 2」で作成した円が上っていく機能を実現する「Circleクラス」の他に、三角形が上っていく機能を実現する「Triangleクラス」を作成した場合、ふたつのクラスが似ていることに気づきます。

class Triangle{
float x;
float y;
float vy;
float size;
float gray;
Triangle(){
x = random(width);
y = random(height);
vy = random(1, 3);
size = random(5, 40);
gray = random(255);
}
void display(){
fill(gray);
triangle(x, y-size/2, x-size/2,y+size/2, x+size/2, y+size/2);
}
void move(){
y -= vy;
}
}

3.親クラスの作成

このような場合「BaseObjectクラス」(親クラス)を作成し、「Circleクラス」と「Triangle」クラスの共通する部分を親クラスに記述することで、同じようなコードの重複を避けられ、わかりやすいコードが実現できます。

class BaseObject {
float x;
float y;
float vy;
float size;
float gray;
BaseObject() {
x = random(width);
y = random(height);
vy = random(1, 3);
size = random(5, 40);
gray = random(255);
}
void display() {
}
void move() {
y -= vy;
}
}

それぞれの子クラスには、親クラスを継承したことを記述した上で、親クラスと異なる部分だけを記述します。

以下のように子クラスでdisplay()関数を定義することで、親クラスのdisplay()関数が上書きされます。

子クラスのCircleクラス

class Circle extends BaseObject{
void display(){
fill(gray);
ellipse(x, y, size, size);
}
}

子クラスのTriangleクラス

class Triangle extends BaseObject{
void display(){
fill(gray);
triangle(x, y-size/2, x-size/2,y+size/2, x+size/2, y+size/2);
}
}

4.コード例

親クラスで変数/関数の追加/変更を行い、ランダムな色で発生した50個の円と50個の三角形が画面上を動き回るコード例です。

子クラスである、Circle、Triangleクラスは、それぞれ違いのみを定義した簡潔なクラスになっていることがわかります。

class BaseObject {
float x;
float y;
float vx;
float vy;
float size;
float r;
float g;
float b;
BaseObject() {
x = random(width);
y = random(height);
vx = random(-3, 3);
vy = random(-3, 3);
size = random(5, 40);
r = random(255);
g = random(255);
b = random(255);
}
void display() {
}
void move() {
y -= vy;
x -= vx;
if (x<0 || x>width) vx = -vx;
if (y<0 || y>width) vy = -vy;
}
}
class Circle extends BaseObject{
void display(){
fill(r,g,b);
ellipse(x, y, size, size);
}
}
class Triangle extends BaseObject{
void display(){
fill(r,g,b);
triangle(x, y-size/2, x-size/2,y+size/2, x+size/2, y+size/2);
}
}
int n = 50;
Circle[] c = new Circle[n];
Triangle[] t= new Triangle[n];
void setup(){
noStroke();
size(1000,600);
for(int i=0; i<n; i++){
c[i] = new Circle();
t[i] = new Triangle();
}
}
void draw(){
background(255);
for(int i=0; i<n; i++){
c[i].display();
c[i].move();
t[i].display();
t[i].move();
}
}