(Chapter written by Jérôme Vouillon and Didier Rémy)
This chapter gives an overview of the object-oriented features of
Objective Caml.
3.1 Classes and objects
3.2 Reference to self
3.3 Initializers
3.4 Virtual methods
3.5 Private methods
3.6 Class interfaces
3.7 Inheritance
3.8 Multiple inheritance
3.9 Parameterized classes
3.10 Using coercions
3.11 Functional objects
3.12 Cloning objects
3.13 Recursive classes
3.14 Binary methods
3.15 Friends
The class point below defines one instance variable x and two methods
get_x and move. The initial value of the instance variable is 0.
The variable x is declared mutable, so the method move can change
its value.
#class point =
object
val mutable x = 0
method get_x = x
method move d = x <- x + d
end;;
class point :
object method get_x : int method move : int -> unit val mutable x : int end
We now create a new point p, instance of the point class.
#let p = new point;;
val p : point = <obj>
Note that the type of p is point. This is an abbreviation
automatically defined by the class definition above. It stands for the
object type <get_x : int; move : int -> unit>, listing the methods
of class point along with their types.
We now invoke some methods to p:
#p#get_x;;
- : int = 0
#p#move 3;;
- : unit = ()
#p#get_x;;
- : int = 3
The evaluation of the body of a class only takes place at object
creation time. Therefore, in the following example, the instance
variable x is initialized to different values for two different
objects.
#let x0 = ref 0;;
val x0 : int ref = {contents = 0}
#