D-programming-abstract-classes

提供:Dev Guides
移動先:案内検索

Dプログラミング-抽象クラス

抽象化とは、OOPでクラスを抽象化する機能のことです。 抽象クラスは、インスタンス化できないクラスです。 クラスの他のすべての機能は引き続き存在し、そのフィールド、メソッド、およびコンストラクターはすべて同じ方法でアクセスされます。 抽象クラスのインスタンスを作成することはできません。

クラスが抽象クラスであり、インスタンス化できない場合、そのクラスはサブクラスでない限りあまり使用されません。 これは通常、設計段階で抽象クラスがどのように発生するかです。 親クラスには子クラスのコレクションの共通機能が含まれていますが、親クラス自体は抽象的すぎて単独では使用できません。

Dで抽象クラスを使用する

*abstract* キーワードを使用して、クラスの抽象を宣言します。 キーワードは、クラスキーワードの前のどこかのクラス宣言に表示されます。 以下に、抽象クラスを継承して使用する方法の例を示します。

import std.stdio;
import std.string;
import std.datetime;

abstract class Person {
   int birthYear, birthDay, birthMonth;
   string name;

   int getAge() {
      SysTime sysTime = Clock.currTime();
      return sysTime.year - birthYear;
   }
}

class Employee : Person {
   int empID;
}

void main() {
   Employee emp = new Employee();
   emp.empID = 101;
   emp.birthYear = 1980;
   emp.birthDay = 10;
   emp.birthMonth = 10;
   emp.name = "Emp1";

   writeln(emp.name);
   writeln(emp.getAge);
}

上記のプログラムをコンパイルして実行すると、次の出力が得られます。

Emp1
37

抽象関数

関数と同様に、クラスも抽象的です。 そのような関数の実装は、そのクラスでは指定されていませんが、抽象関数を持つクラスを継承するクラスで提供する必要があります。 上記の例は、抽象関数で更新されています。

import std.stdio;
import std.string;
import std.datetime;

abstract class Person {
   int birthYear, birthDay, birthMonth;
   string name;

   int getAge() {
      SysTime sysTime = Clock.currTime();
      return sysTime.year - birthYear;
   }
   abstract void print();
}
class Employee : Person {
   int empID;

   override void print() {
      writeln("The employee details are as follows:");
      writeln("Emp ID: ", this.empID);
      writeln("Emp Name: ", this.name);
      writeln("Age: ",this.getAge);
   }
}

void main() {
   Employee emp = new Employee();
   emp.empID = 101;
   emp.birthYear = 1980;
   emp.birthDay = 10;
   emp.birthMonth = 10;
   emp.name = "Emp1";
   emp.print();
}

上記のプログラムをコンパイルして実行すると、次の出力が得られます。

The employee details are as follows:
Emp ID: 101
Emp Name: Emp1
Age: 37