Home News DOC Class DL Others Cooker
Documents  >  Tutorial  >  Encapsulation
Encapsulation

Encapsulation is the restriction of access to members.


Table of contents:


Example

open member

closed member

Class-level encapsulation

Example

The example class defined on 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

Although it does not appear in the above example, 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

32 to 34 line of the above example are:

32:

open method example Add(example ve) // Same name, different argument.

33:

return new example(x + ve.x, y + ve.y);

34:

em // Abbreviation.

They are accessing the field of the argument "ve" of the example class via the dot operator.

Since the Add(example) method is a member of the example class, it can access up to the closed member for an instance of the example class.


Inside a class definition, you have unlimited access to closed members of all instances of that class.

Next
Previous
Copyright © Rice All rights reserved.