English 中文(简体)
D Programming - Abstract Classes
  • 时间:2024-12-22

D Programming - Abstract Classes


Previous Page Next Page  

Abstraction refers to the abipty to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionapty of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionapty of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Using Abstract Class in D

Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword. The following shows an example of how abstract class can be inherited and used.

Example

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); 
}

When we compile and run the above program, we will get the following output.

Emp1
37

Abstract Functions

Similar to functions, classes can also be abstract. The implementation of such function is not given in its class but should be provided in the class that inherits the class with abstract function. The above example is updated with abstract function.

Example

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(); 
}

When we compile and run the above program, we will get the following output.

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