e9741e95d83ff923e27c9f9e2d6f47c06c4f86b8
[nit.git] / doc / manual / attribute.md
1 # Attributes
2
3 `var`, used inside concrete and abstract classes, declares attributes. Attributes require a static type and can possibly have an initial value (it may be any kind of expression, even including
4 `self`)
5
6 ~~~
7 class Foo
8     var i: Int = 5
9     fun dec(x: Int)
10     do
11         var k = self.i
12         if k > x then self.i = k - x else self.i = 0
13     end
14 end
15 ~~~
16
17 Note that from an API point of view, there is no way to distinguish the read access of an attribute with a normal method neither to distinguish a write access of an attribute with a setter. Therefore, the read access of an attribute is called a getter while the write access is called a setter.
18
19 ~~~
20 var x = foo.bar # Is bar an attribute or a method?
21 foo.bar = y # Is bar an attribute or a setter?
22 # In fact, we do not need to know.
23 ~~~
24
25 ## Visibility of Attributes
26
27 By default, a getter is public and a setter is private. The visibility of getters can be precised with the `private` or `protected` keywords. The visibility of setters can be specified with an
28 additional `writable` keyword.
29
30 ~~~
31 class Foo
32     var pub_pri: X
33     protected var pro_pri: X
34     var pub_pub: X is writable
35     private var pri_pro: X is protected writable
36     var pub_pri2: X is private writable # the default
37 end
38 ~~~
39
40 ## Redefinition of Attributes
41
42 Getters and setters of attributes behave like genuine methods that can be inherited and redefined. Getters and setters can also redefine inherited methods. `redef var` declares that the getter is
43 a redefinition while `redef writable` declares that the setter is a redefinition.
44
45 ~~~
46 interface Foo
47     fun derp: Int is abstract
48     fun derp=(o: Int) is abstract
49 end
50 class Bar
51     super Foo
52     redef var derp: Int redef writable
53 end
54 class Baz
55     super Bar
56     redef fun derp do ...
57     redef fun derp=(o) do ...
58 end
59 ~~~