Encapsulation and Protection Attributes

This commit is contained in:
rillk500 2020-07-10 12:43:27 +06:00
parent d2082174c5
commit 774aecf3e8
2 changed files with 78 additions and 0 deletions

View File

@ -0,0 +1,64 @@
module encap_protec_attrib;
// ***** public by default ******
// => can be both accessed and modified
struct Person {
string name; // or => public string name;
int age;
}
// ****** private members ******
// => cannot be modified, but can be accessed through get... functions
struct Person2 {
private string name;
private int age;
string getName() {
return name;
}
int getAge() {
return age;
}
}
// specifying protection attributes at a modular level
private void foo() { /* or struct/class/etc */ }
// ****** package protection attribute ******
// animal.cat contains: package void foo() { ... }
// it can be accessed in any other module inside the animal package
// ****** protected members ******
// => can be accessed by the module that defines it and by any class that inherits from it
class Person3 {
string name;
int age;
protected int id;
// this(...) { ... }
// ...
}
// ****** defining protection attribtes ******
// 1) java style
private void hello() { }
// 2) c++ style
public:
void hello() { }
// ...
// 3) block style
protected {
void hello() { }
}

View File

@ -0,0 +1,14 @@
import std.stdio;
import encap_protec_attrib;
void main() {
// John's members can be freely accessed and modified
Person John = Person("John", 35);
writeln("Person: ", John.name, ", ", John.age);
// Mary's members can be accessed through get... functions, but can't be modified
Person2 Mary = Person2("Mary", 21);
writeln("Person: ", Mary.name, ", ", Mary.age); // ERROR! => no such property: name, age (because it's private)
writeln("Person: ", Mary.getName(), ", ", Mary.getAge()); // works! => a copy/value is returned
}