next up previous
Next: Méthodes abstraites Up: Autres constructions Previous: Autres constructions

Initialisation

Une classe peut incorporer une méthode anonyme qui est declenchée immédiatement après construction d'un objet de cette classe. Cette méthode est définie à l'aide du mot-clé initializer. Elle peut réaliser n'importe quel calcul, et a accès à self et aux variables d'instance:

class point init =
 object(self) 
  val mutable x = init
  method getx = x
  method print = print_int x

  initializer print_string"Nouveau point aux coordonnees: ";
             self#print; print_newline()
end;;

class point :
  int -> 
 object 
  val mutable x : int 
  method getx : int 
  method print : unit 
 end

class colorpoint xinit cinit =
 object(self)
  inherit point xinit as pointsup
  inherit color cinit as colorsup
  .....
  initializer print_string"Nouveau point colore de couleur: ";
             print_string self#getcolor; print_newline()
end;;  

class colorpoint :
  int ->
  string ->
  object
    val mutable color : string
    val mutable x : int
    method getcolor : string
    method setcolor : string -> unit
    method getx : int
    method print : unit
  end
Les méthodes d'initialisation ne peuvent pas être redéfinies. Elles s'exécutent séquentiellement, comme le montre l'exemple suivant où les initialisations pour un point et pour un point coloré se succèdent lors de la création d'un point coloré:
# let p = new point 3;;
Nouveau point aux coordonnees: 3
val p : point = <obj>

# let pc = new point_colore 4 "blue";;
Nouveau point aux coordonnees: (4 ,blue)
Nouveau point colore de couleur: blue
val pc : point_colore = <obj>

Notez, lors de la création de pc, que la méthode print employée par l'initialisation d'un point n'est pas celle des points, mais celle de l'objet courant (ici, self) = pc).



Maria-Viginia Aponte
2001-03-28