Encapsulation
Encapsulation is the restriction of access to members.
Table of contents:
Example
The example class defined up to the previous page is:
1: | class example |
2: | int x; |
3: | int y; |
4: | open fitter example() // Default fitter |
5: | x = 0; |
6: | y = 0; |
7: | endfitter |
8: | open fitter example(int xx, int yy) // Fitter with two arguments. |
9: | x = xx; |
10: | y = yy; |
11: | ef // Abbreviation. |
12: | open setter X(int val) |
13: | x = val; |
14: | endsetter |
15: | open getter int X |
16: | return x; |
17: | endgetter |
18: | open setter Y(int val) |
19: | y = val; |
20: | es // Abbreviation. |
21: | open getter int Y |
22: | return y; |
23: | eg // Abbreviation. |
24: | open method void Clear() |
25: | x = 0; |
26: | y = 0; |
27: | return; // Optional, not required. |
28: | endmethod |
29: | open method example Add(int vx, int vy) |
30: | return new example(x + vx, y + vy); |
31: | endmethod |
32: | open method example Add(example ve) // Same name, different argument. |
33: | return new example(x + ve.x, y + ve.y); |
34: | em // Abbreviation. |
35: | endclass |
open member
Members whose definition start with the access controller "open" are called open member.
The open member can be called from outside of the class definition via the dot operator.
closed member
Members whose definition start with the access controller "closed" are called closed member. Fields are also closed member.
The closed member cannot be called from outside of the class definition via the dot operator.
Class-level encapsulation
Let's think about code that uses the example class.
1: | example ex1 = new example(10, 10); |
2: | example ex2 = new example(10, 10); |
3: | example ex3 = ex1.Add(ex2); // ex3.x == 20 ex3.y == 20 |
The ex1 and ex2 are different instances of the same class. Fields, closed member, of the ex2 has been accessed in the Add(example) method of the ex1.
32: | open method example Add(example ve) // Same name, different argument. |
33: | return new example(x + ve.x, y + ve.y); |
34: | em // Abbreviation. |
Rice has unlimited access to closed members of all instances of a class, only inside the class definition. Such encapsulation is called "class level encapsulation".