Inheritance is an object oriented programming concept that allows other classes to use the properties and method of a class. In D programming, the class inherited is the base
class and the class inheriting is the derived
class. Let’s see an example.
import std.stdio;// Base classclass Shape {public:void dimension(int h,int w) {height = h;width = w;}int width;int height;}// Derived classclass Square: Shape {public:int findArea() {return (width * height);}}void main() {Square Sqr = new Square();Sqr.dimension(9,9);// Print the area of the object.writeln("Total area of square: ", Sqr.findArea());}
In the example above, we create an object of the base class, Shape
, to take dimensions. We also create an object of the derived class, Square
, to calculate the area.
Line 3: We define the base class, shape
.
Line 4: We make it publicly accessible by adding the public
keyword.
Lines 5–8: We declare a method, dimension()
, to receive the square’s dimensions.
Line 9 and 10: We define the variable we would use to make the area calculation.
Line 13: We create our derived class to inherit the base class. Notice the :
used after the name of the derived class.
Line 14: We make it publicly accessible by adding the public
keyword.
Lines 15–18: We declare a method, findArea()
, to calculate the square’s area.
Line 20: We instantiate the derived class to a Sqr
variable.
Line 21: We access the dimension()
method of the base class, where we passed the square’s values.
Line 23: We finally call the Sqr.findArea()
to output the calculation’s result.