doc/manual: put back the manual in the main repository
[nit.git] / doc / manual / class.md
1 # Classes
2
3 `interface`, `abstract class`, `class` and `enum` are the four kinds of classes. All these classes can be in multiple inheritance, can define new methods and redefine inherited method (yes, even interfaces).
4
5 Here are the differences:
6
7 -   interfaces can only specialize other interfaces, cannot have     attributes, cannot have constructors, cannot be instantiated.
8
9 -   abstract classes cannot specialize enums, can have attributes, must have constructors, cannot be instantiated.
10
11 -   concrete classes (i.e. `class`) cannot specialize enums, can have attributes, must have constructors, can be instantiated.
12
13 -   enums (e.g. `Int` or `Bool`) can only specialize interfaces, cannot have attributes, cannot have constructors, have proper instances but they are not instantiated by the programmer—it means no `new Int`. Note that at this point there is no user-defined enums.
14
15 All kinds of classes must have a name, can have some superclasses and can have some definitions of properties. Properties are methods, attributes, constructors and virtual types. All kinds of classes can also be generic. When we talk about “classes” in general, it means all these four kinds. We say “concrete classes” to designate only the classes declared with the `class` keyword alone.
16
17 ## Class Specialization
18
19 `super` declares superclasses. Classes inherit methods, attributes and virtual-types defined in their superclasses. Currently, constructors are inherited in a specific manner.
20
21 `Object` is the root of the class hierarchy. It is an interface and all other kinds of classes are implicitly a subclass of `Object`.
22
23 There is no repeated inheritance nor private inheritance. The specialization between classes is transitive, therefore `super` declarations are superfluous (thus ignored).
24
25 ## Class Refinement
26
27 `redef` allows modules to refine imported classes (even basic ones). Refining a class means:
28
29 -   adding new properties: methods, attributes, constructors, virtual types;
30
31 -   redefining existing properties: methods and constructors;
32
33 -   adding new superclasses.
34
35 Note that the kind or the visibility of a class cannot be changed by a refinement. Therefore, it is allowed to just write `redef class X` whatever is the kind or the visibility of `X`.
36
37 In programs, the real instantiated classes are always the combination of all their refinements.
38
39 ~~~
40 redef class Int
41     fun fib: Int
42     do
43         if self < 2 then return self
44         return (self-1).fib + (self-2).fib
45     end
46 end
47 # Now all integers have the fib method
48 print 15.fib # outputs 610
49 ~~~