Example of Encapsulation in D

Let’s see how encapsulation works with the help of an example.

We'll cover the following

Encapsulation example

Let’s define the Student struct and the School class by taking advantage of encapsulation, and let’s use them in a short test program.

This example program will consist of three files. As you remember from the previous chapter, being parts of the school package, two of these files will be under the “school” directory:

  • “school/student.d”: The student module that defines the Student struct

  • “school/school.d”: The school module that defines the School class

  • “main.d”: A short test program

Here is the “school/student.d” file:

Get hands-on with 1000+ tech skills courses.