Browse thread
ocaml example at http://w3.one.net/~jweirich/oostuff/
- Pixel
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Pixel <pixel@m...> |
| Subject: | ocaml example at http://w3.one.net/~jweirich/oostuff/ |
(*
Here is little rework of the example that i find nicer :)
- it now shows the ability to subtype when inheriting...
- use of printf for cleanup
- use of List.iter instead of explicitly doing it via recursion
- removed the "int" typing of class constructors, caml doesn't need any help,
even if keeping them may be clearer
cu Pixel.
*)
class virtual shape initx inity =
object (self)
val mutable x = initx
val mutable y = inity
(* get the x & y coordinates for the object *)
method getX = x
method getY = y
(* set the x & y coordinates for the object *)
method setX newx = x <- newx
method setY newy = y <- newy
(* move the x & y position of the object *)
method moveTo newx newy =
self#setX newx;
self#setY newy
method rMoveTo deltax deltay =
self#setX (self#getX + deltax);
self#setY (self#getY + deltay)
(* draw method is effectively abstract *)
method virtual draw : unit
end
class rectangle initx inity initwidth initheight =
object (self)
inherit shape initx inity
val mutable width = initwidth
val mutable height = initheight
(* get the width & height of the object *)
method getWidth = width
method getHeight = height
(* set the width & height of the object *)
method setWidth newwidth = width <- newwidth
method setHeight newheight = height <- newheight
(* draw the rectangle *)
method draw =
Printf.printf "Drawing a Rectangle at:(%d,%d), width %d, height %d\n"
self#getX
self#getY
self#getWidth
self#getHeight
end
class circle initx inity initradius =
object (self)
inherit shape initx inity
val mutable radius = initradius
(* get the radius of the object *)
method getRadius = radius
(* set the radius of the object *)
method setRadius newradius = radius <- newradius
(* draw the circle *)
method draw =
Printf.printf "Drawing a Circle at:(%d,%d), radius %d\n"
self#getX
self#getY
self#getRadius
end
let main () =
(* set up lists to hold the shapes *)
let (scribble : shape list) = [
(new rectangle 10 20 5 6 :> shape) ;
(new circle 15 25 8 :> shape)
] in
(* iterate through the lists and handle shapes polymorphically *)
List.iter (fun o ->
o#draw;
o#rMoveTo 100 100;
o#draw
) scribble;
(* call a rectangle specific instance *)
let arectangle = new rectangle 0 0 15 15 in
arectangle#draw;
arectangle#setWidth 30;
arectangle#draw;;
main ();;