File: manual005.html

package info (click to toggle)
ocaml-doc 3.09-1
  • links: PTS
  • area: non-free
  • in suites: etch, etch-m68k
  • size: 10,428 kB
  • ctags: 4,963
  • sloc: ml: 9,244; makefile: 2,413; ansic: 122; sh: 49; asm: 17
file content (1568 lines) | stat: -rw-r--r-- 66,190 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
            "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>



<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="hevea 1.08">
<LINK rel="stylesheet" type="text/css" href="manual.css">
<TITLE>
Objects in Caml
</TITLE>
</HEAD>
<BODY >
<A HREF="manual004.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<A HREF="manual006.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<HR>

<H1 CLASS="chapter"><A NAME="htoc18">Chapter&nbsp;3</A>&nbsp;&nbsp;Objects in Caml</H1>
<A NAME="c:objectexamples"></A>

<I>(Chapter written by Jrme Vouillon, Didier Rmy and Jacques Garrigue)</I><BR>
<BR>
<BR>
<BR>
<BR>
<BR>
This chapter gives an overview of the object-oriented features of
Objective Caml.
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
Note that the relation between object, class and type
in Objective Caml is very different from that in main stream
object-oriented languages like Java or C++, so that you should not
assume that similar keywords mean the same thing.<BR>
</div>
<BR>
<A HREF="#ss:classes-and-objects">3.1</A> Classes and objects<BR>
<A HREF="#ss:immediate-objects">3.2</A> Immediate objects<BR>
<A HREF="#ss:reference-to-self">3.3</A> Reference to self<BR>
<A HREF="#ss:initializers">3.4</A> Initializers<BR>
<A HREF="#ss:virtual-methods">3.5</A> Virtual methods<BR>
<A HREF="#ss:private-methods">3.6</A> Private methods<BR>
<A HREF="#ss:class-interfaces">3.7</A> Class interfaces<BR>
<A HREF="#ss:inheritance">3.8</A> Inheritance<BR>
<A HREF="#ss:multiple-inheritance">3.9</A> Multiple inheritance<BR>
<A HREF="#ss:parameterized-classes">3.10</A> Parameterized classes<BR>
<A HREF="#ss:polymorphic-methods">3.11</A> Polymorphic methods<BR>
<A HREF="#ss:using-coercions">3.12</A> Using coercions<BR>
<A HREF="#ss:functional-objects">3.13</A> Functional objects<BR>
<A HREF="#ss:cloning-objects">3.14</A> Cloning objects<BR>
<A HREF="#ss:recursive-classes">3.15</A> Recursive classes<BR>
<A HREF="#ss:binary-methods">3.16</A> Binary methods<BR>
<A HREF="#ss:friends">3.17</A> Friends<BR>
<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc19">3.1</A>&nbsp;&nbsp;Classes and objects</H2>

<A NAME="ss:classes-and-objects"></A> 
The class <TT>point</TT> below defines one instance variable <TT>x</TT> and two methods
<TT>get_x</TT> and <TT>move</TT>. The initial value of the instance variable is <TT>0</TT>.
The variable <TT>x</TT> is declared mutable, so the method <TT>move</TT> can change
its value.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point =
   object 
     val mutable x = 0
     method get_x = x
     method move d = x &lt;- x + d
   end;;
</FONT><FONT COLOR=maroon>class point :
  object val mutable x : int method get_x : int method move : int -&gt; unit end
</FONT></PRE>
We now create a new point <TT>p</TT>, instance of the <TT>point</TT> class.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new point;;
</FONT><FONT COLOR=maroon>val p : point = &lt;obj&gt;
</FONT></PRE>
Note that the type of <TT>p</TT> is <TT>point</TT>. This is an abbreviation
automatically defined by the class definition above. It stands for the
object type <TT>&lt;get_x : int; move : int -&gt; unit&gt;</TT>, listing the methods
of class <TT>point</TT> along with their types.<BR>
<BR>
We now invoke some methods to <TT>p</TT>:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>p#get_x;;
</FONT><FONT COLOR=maroon>- : int = 0
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#move 3;;
</FONT>- : unit = ()
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#get_x;;
</FONT>- : int = 3
</FONT></PRE>
The evaluation of the body of a class only takes place at object
creation time. Therefore, in the following example, the instance
variable <TT>x</TT> is initialized to different values for two different
objects.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let x0 = ref 0;;
</FONT><FONT COLOR=maroon>val x0 : int ref = {contents = 0}
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class point =
   object 
     val mutable x = incr x0; !x0
     method get_x = x
     method move d = x &lt;- x + d
   end;;
</FONT>class point :
  object val mutable x : int method get_x : int method move : int -&gt; unit end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>new point#get_x;;
</FONT>- : int = 1
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>new point#get_x;;
</FONT>- : int = 2
</FONT></PRE>
The class <TT>point</TT> can also be abstracted over the initial values of
the <TT>x</TT> coordinate.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point = fun x_init -&gt; 
   object 
     val mutable x = x_init
     method get_x = x
     method move d = x &lt;- x + d
   end;;
</FONT><FONT COLOR=maroon>class point :
  int -&gt;
  object val mutable x : int method get_x : int method move : int -&gt; unit end
</FONT></PRE>
Like in function definitions, the definition above can be
abbreviated as:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point x_init =
   object 
     val mutable x = x_init
     method get_x = x
     method move d = x &lt;- x + d
   end;;
</FONT><FONT COLOR=maroon>class point :
  int -&gt;
  object val mutable x : int method get_x : int method move : int -&gt; unit end
</FONT></PRE>
An instance of the class <TT>point</TT> is now a function that expects an
initial parameter to create a point object:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>new point;;
</FONT><FONT COLOR=maroon>- : int -&gt; point = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new point 7;;
</FONT>val p : point = &lt;obj&gt;
</FONT></PRE>
The parameter <TT>x_init</TT> is, of course, visible in the whole body of the
definition, including methods. For instance, the method <TT>get_offset</TT>
in the class below returns the position of the object relative to its 
initial position.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point x_init =
   object 
     val mutable x = x_init
     method get_x = x
     method get_offset = x - x_init
     method move d = x &lt;- x + d 
   end;;
</FONT><FONT COLOR=maroon>class point :
  int -&gt;
  object
    val mutable x : int
    method get_offset : int
    method get_x : int
    method move : int -&gt; unit
  end
</FONT></PRE>
Expressions can be evaluated and bound before defining the object body
of the class. This is useful to enforce invariants. For instance,
points can be automatically adjusted to the nearest point on a grid,
as follows:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class adjusted_point x_init =
   let origin = (x_init / 10) * 10 in
   object 
     val mutable x = origin
     method get_x = x
     method get_offset = x - origin
     method move d = x &lt;- x + d
   end;;
</FONT><FONT COLOR=maroon>class adjusted_point :
  int -&gt;
  object
    val mutable x : int
    method get_offset : int
    method get_x : int
    method move : int -&gt; unit
  end
</FONT></PRE>
(One could also raise an exception if the <TT>x_init</TT> coordinate is not
on the grid.) In fact, the same effect could here be obtained by
calling the definition of class <TT>point</TT> with the value of the
<TT>origin</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class adjusted_point x_init =  point ((x_init / 10) * 10);;
</FONT><FONT COLOR=maroon>class adjusted_point : int -&gt; point
</FONT></PRE>
An alternative solution would have been to define the adjustment in 
a special allocation function:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let new_adjusted_point x_init = new point ((x_init / 10) * 10);;
</FONT><FONT COLOR=maroon>val new_adjusted_point : int -&gt; point = &lt;fun&gt;
</FONT></PRE>
However, the former pattern is generally more appropriate, since 
the code for adjustment is part of the definition of the class and will be
inherited.<BR>
<BR>
This ability provides class constructors as can be found in other
languages. Several constructors can be defined this way to build objects of
the same class but with different initialization patterns; an
alternative is to use initializers, as decribed below in section
<A HREF="#ss:initializers">3.4</A>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc20">3.2</A>&nbsp;&nbsp;Immediate objects</H2>

<A NAME="ss:immediate-objects"></A>
There is another, more direct way to create an object: create it
without going through a class.<BR>
<BR>
The syntax is exactly the same as for class expressions, but the
result is a single object rather than a class. All the constructs
described in the rest of this section also apply to immediate objects.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let p =
   object 
     val mutable x = 0
     method get_x = x
     method move d = x &lt;- x + d
   end;;
</FONT><FONT COLOR=maroon>val p : &lt; get_x : int; move : int -&gt; unit &gt; = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#get_x;;
</FONT>- : int = 0
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#move 3;;
</FONT>- : unit = ()
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#get_x;;
</FONT>- : int = 3
</FONT></PRE>
Unlike classes, which cannot be defined inside an expression,
immediate objects can appear anywhere, using variables from their
environment.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let minmax x y =
   if x &lt; y then object method min = x method max = y end
   else object method min = y method max = x end;;
</FONT><FONT COLOR=maroon>val minmax : 'a -&gt; 'a -&gt; &lt; max : 'a; min : 'a &gt; = &lt;fun&gt;
</FONT></PRE>
Immediate objects have two weaknesses compared to classes: their types
are not abbreviated, and you cannot inherit from them. But these two
weaknesses can be advantages in some situations, as we will see
in sections <A HREF="#ss:reference-to-self">3.3</A> and <A HREF="#ss:parameterized-classes">3.10</A>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc21">3.3</A>&nbsp;&nbsp;Reference to self</H2>

<A NAME="ss:reference-to-self"></A>
A method or an initializer can send messages to self (that is,
the current object). For that, self must be explicitly bound, here to
the variable <TT>s</TT> (<TT>s</TT> could be any identifier, even though we will
often choose the name <TT>self</TT>.)
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class printable_point x_init =
   object (s)
     val mutable x = x_init
     method get_x = x
     method move d = x &lt;- x + d
     method print = print_int s#get_x
   end;;
</FONT><FONT COLOR=maroon>class printable_point :
  int -&gt;
  object
    val mutable x : int
    method get_x : int
    method move : int -&gt; unit
    method print : unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new printable_point 7;;
</FONT>val p : printable_point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#print;;
</FONT>7- : unit = ()
</FONT></PRE>
Dynamically, the variable <TT>s</TT> is bound at the invocation of a method. In
particular, when the class <TT>printable_point</TT> is inherited, the variable
<TT>s</TT> will be correctly bound to the object of the subclass. <BR>
<BR>
A common problem with self is that, as its type may be extended in
subclasses, you cannot fix it in advance. Here is a simple example.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let ints = ref [];;
</FONT><FONT COLOR=maroon>val ints : '_a list ref = {contents = []}
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class my_int =
   object (self)
     method n = 1
     method register = ints := <U>self</U> :: !ints
   end;;
</FONT>This expression has type &lt; n : int; register : 'a; .. &gt;
but is here used with type 'b
Self type cannot escape its class
</FONT></PRE>
You can ignore the first two lines of the error message. What matters
is the last one: putting self into an external reference would make it
impossible to extend it afterwards.
We will see in section <A HREF="#ss:using-coercions">3.12</A> a workaround to this
problem.
Note however that, since immediate objects are not extensible, the
problem does not occur with them.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let my_int =
   object (self)
     method n = 1
     method register = ints := self :: !ints
   end;;
</FONT><FONT COLOR=maroon>val my_int : &lt; n : int; register : unit &gt; = &lt;obj&gt;
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc22">3.4</A>&nbsp;&nbsp;Initializers</H2>

<A NAME="ss:initializers"></A>
Let-bindings within class definitions are evaluated before the object
is constructed. It is also possible to evaluate an expression
immediately after the object has been built. Such code is written as
an anonymous hidden method called an initializer. Therefore, is can
access self and the instance variables.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class printable_point x_init =
   let origin = (x_init / 10) * 10 in
   object (self)
     val mutable x = origin
     method get_x = x
     method move d = x &lt;- x + d
     method print = print_int self#get_x
     initializer print_string "new point at "; self#print; print_newline()
   end;;
</FONT><FONT COLOR=maroon>class printable_point :
  int -&gt;
  object
    val mutable x : int
    method get_x : int
    method move : int -&gt; unit
    method print : unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new printable_point 17;;
</FONT>new point at 10
val p : printable_point = &lt;obj&gt;
</FONT></PRE>
Initializers cannot be overridden. On the contrary, all initializers are
evaluated sequentially. 
Initializers are particularly useful to enforce invariants. 
Another example can be seen in section <A HREF="manual007.html#ss:bank-accounts">5.1</A>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc23">3.5</A>&nbsp;&nbsp;Virtual methods</H2>

<A NAME="ss:virtual-methods"></A>
It is possible to declare a method without actually defining it, using
the keyword <TT>virtual</TT>. This method will be provided later in
subclasses. A class containing virtual methods must be flagged
<TT>virtual</TT>, and cannot be instantiated (that is, no object of this class
can be created). It still defines type abbreviations (treating virtual methods
as other methods.)
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class virtual abstract_point x_init =
   object (self)
     val mutable x = x_init
     method virtual get_x : int
     method get_offset = self#get_x - x_init
     method virtual move : int -&gt; unit
   end;;
</FONT><FONT COLOR=maroon>class virtual abstract_point :
  int -&gt;
  object
    val mutable x : int
    method get_offset : int
    method virtual get_x : int
    method virtual move : int -&gt; unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class point x_init =
   object
     inherit abstract_point x_init
     method get_x = x
     method move d = x &lt;- x + d 
   end;;
</FONT>class point :
  int -&gt;
  object
    val mutable x : int
    method get_offset : int
    method get_x : int
    method move : int -&gt; unit
  end
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc24">3.6</A>&nbsp;&nbsp;Private methods</H2>

<A NAME="ss:private-methods"></A>
Private methods are methods that do not appear in object interfaces.
They can only be invoked from other methods of the same object.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class restricted_point x_init =
   object (self)
     val mutable x = x_init
     method get_x = x
     method private move d = x &lt;- x + d
     method bump = self#move 1
   end;;
</FONT><FONT COLOR=maroon>class restricted_point :
  int -&gt;
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method private move : int -&gt; unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new restricted_point 0;;
</FONT>val p : restricted_point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue><U>p</U>#move 10;;
</FONT>This expression has type restricted_point
It has no method move
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#bump;;
</FONT>- : unit = ()
</FONT></PRE>
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
Note that this is not the same thing as private and protected methods
in Java or C++, which can be called from other objects of the same
class. This is a direct consequence of the independence between types
and classes in Objective Caml: two unrelated classes may produce
objects of the same type, and there is no way at the type level to
ensure that an object comes from a specific class. However a possible
encoding of friend methods is given in section <A HREF="#ss:friends">3.17</A>.<BR>
</div>
<BR>
Private methods are inherited (they are by default visible in subclasses), 
unless they are hidden by signature matching, as described below.<BR>
<BR>
Private methods can be made public in a subclass. 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point_again x =
   object (self)
     inherit restricted_point x
     method virtual move : _
   end;;
</FONT><FONT COLOR=maroon>class point_again :
  int -&gt;
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method move : int -&gt; unit
  end
</FONT></PRE>
The annotation <TT>virtual</TT> here is only used to mention a method without
providing its definition. Since we didn't add the <TT>private</TT>
annotation, this makes the method public, keeping the original
definition.<BR>
<BR>
An alternative definition is
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point_again x =
   object (self : &lt; move : _; ..&gt; )
     inherit restricted_point x
   end;;
</FONT><FONT COLOR=maroon>class point_again :
  int -&gt;
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method move : int -&gt; unit
  end
</FONT></PRE>
The constraint on self's type is requiring a public <TT>move</TT> method, and
this is sufficient to override <TT>private</TT>.<BR>
<BR>
One could think that a private method should remain private in a subclass. 
However, since the method is visible in a subclass, it is always possible
to pick its code and define a method of the same name that runs that
code, so yet another (heavier) solution would be:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class point_again x =
   object
     inherit restricted_point x as super
     method move = super#move 
   end;;
</FONT><FONT COLOR=maroon>class point_again :
  int -&gt;
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method move : int -&gt; unit
  end
</FONT></PRE>
Of course, private methods can also be virtual. Then, the keywords must
appear in this order <TT>method private virtual</TT>. <BR>
<BR>

<H2 CLASS="section"><A NAME="htoc25">3.7</A>&nbsp;&nbsp;Class interfaces</H2>

<A NAME="ss:class-interfaces"></A>
Class interfaces are inferred from class definitions. They may also
be defined directly and used to restrict the type of a class. Like class
declarations, they also define a new type abbreviation.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class type restricted_point_type = 
   object
     method get_x : int
     method bump : unit
 end;;
</FONT><FONT COLOR=maroon>class type restricted_point_type =
  object method bump : unit method get_x : int end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>fun (x : restricted_point_type) -&gt; x;;
</FONT>- : restricted_point_type -&gt; restricted_point_type = &lt;fun&gt;
</FONT></PRE>
In addition to program documentation, class interfaces can be used to
constrain the type of a class. Both instance variables and concrete
private methods can be hidden by a class type constraint. Public and
virtual methods, however, cannot. 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class restricted_point' x = (restricted_point x : restricted_point_type);;
</FONT><FONT COLOR=maroon>class restricted_point' : int -&gt; restricted_point_type
</FONT></PRE>
Or, equivalently:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class restricted_point' = (restricted_point : int -&gt; restricted_point_type);;
</FONT><FONT COLOR=maroon>class restricted_point' : int -&gt; restricted_point_type
</FONT></PRE>
The interface of a class can also be specified in a module
signature, and used to restrict the inferred signature of a module. 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>module type POINT = sig 
   class restricted_point' : int -&gt;
     object    
       method get_x : int
       method bump : unit
     end 
 end;;
</FONT><FONT COLOR=maroon>module type POINT =
  sig
    class restricted_point' :
      int -&gt; object method bump : unit method get_x : int end
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>module Point : POINT = struct 
   class restricted_point' = restricted_point
 end;;
</FONT>module Point : POINT
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc26">3.8</A>&nbsp;&nbsp;Inheritance</H2>

<A NAME="ss:inheritance"></A>
We illustrate inheritance by defining a class of colored points that
inherits from the class of points. This class has all instance
variables and all methods of class <TT>point</TT>, plus a new instance
variable <TT>c</TT> and a new method <TT>color</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class colored_point x (c : string) =
   object 
     inherit point x
     val c = c
     method color = c
   end;;
</FONT><FONT COLOR=maroon>class colored_point :
  int -&gt;
  string -&gt;
  object
    val c : string
    val mutable x : int
    method color : string
    method get_offset : int
    method get_x : int
    method move : int -&gt; unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p' = new colored_point 5 "red";;
</FONT>val p' : colored_point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p'#get_x, p'#color;;
</FONT>- : int * string = (5, "red")
</FONT></PRE>
A point and a colored point have incompatible types, since a point has
no method <TT>color</TT>. However, the function <TT>get_x</TT> below is a generic
function applying method <TT>get_x</TT> to any object <TT>p</TT> that has this
method (and possibly some others, which are represented by an ellipsis
in the type). Thus, it applies to both points and colored points.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let get_succ_x p = p#get_x + 1;;
</FONT><FONT COLOR=maroon>val get_succ_x : &lt; get_x : int; .. &gt; -&gt; int = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>get_succ_x p + get_succ_x p';;
</FONT>- : int = 8
</FONT></PRE>
Methods need not be declared previously, as shown by the example:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let set_x p = p#set_x;;
</FONT><FONT COLOR=maroon>val set_x : &lt; set_x : 'a; .. &gt; -&gt; 'a = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let incr p = set_x p (get_succ_x p);;
</FONT>val incr : &lt; get_x : int; set_x : int -&gt; 'a; .. &gt; -&gt; 'a = &lt;fun&gt;
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc27">3.9</A>&nbsp;&nbsp;Multiple inheritance</H2>

<A NAME="ss:multiple-inheritance"></A>
Multiple inheritance is allowed. Only the last definition of a method
is kept: the redefinition in a subclass of a method that was visible in
the parent class overrides the definition in the parent class.
Previous definitions of a method can be reused by binding the related
ancestor. Below, <TT>super</TT> is bound to the ancestor <TT>printable_point</TT>.
The name <TT>super</TT> is a pseudo value identifier that can only be used to
invoke a super-class method, as in <TT>super#print</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class printable_colored_point y c = 
   object (self)
     val c = c
     method color = c
     inherit printable_point y as super
     method print =
       print_string "(";
       super#print;
       print_string ", ";
       print_string (self#color);
       print_string ")"
   end;;
</FONT><FONT COLOR=maroon>class printable_colored_point :
  int -&gt;
  string -&gt;
  object
    val c : string
    val mutable x : int
    method color : string
    method get_x : int
    method move : int -&gt; unit
    method print : unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p' = new printable_colored_point 17 "red";;
</FONT>new point at (10, red)
val p' : printable_colored_point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p'#print;;
</FONT>(10, red)- : unit = ()
</FONT></PRE>
A private method that has been hidden in the parent class is no longer
visible, and is thus not overridden. Since initializers are treated as
private methods, all initializers along the class hierarchy are evaluated,
in the order they are introduced.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc28">3.10</A>&nbsp;&nbsp;Parameterized classes</H2>

<A NAME="ss:parameterized-classes"></A>
Reference cells can be implemented as objects.
The naive definition fails to typecheck:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class<U> ref x_init =
   object 
     val mutable x = x_init
     method get = x
     method set y = x &lt;- y
   end</U>;;
</FONT><FONT COLOR=maroon>Some type variables are unbound in this type:
  class ref :
    'a -&gt;
    object val mutable x : 'a method get : 'a method set : 'a -&gt; unit end
The method get has type 'a where 'a is unbound
</FONT></PRE>
The reason is that at least one of the methods has a polymorphic type
(here, the type of the value stored in the reference cell), thus 
either the class should be parametric, or the method type should be
constrained to a monomorphic type. A monomorphic instance of the class could
be defined by:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ref (x_init:int) =
   object 
     val mutable x = x_init
     method get = x
     method set y = x &lt;- y
   end;;
</FONT><FONT COLOR=maroon>class ref :
  int -&gt;
  object val mutable x : int method get : int method set : int -&gt; unit end
</FONT></PRE>
Note that since immediate objects do not define a class type, the have
no such restriction.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let new_ref x_init =
   object 
     val mutable x = x_init
     method get = x
     method set y = x &lt;- y
   end;;
</FONT><FONT COLOR=maroon>val new_ref : 'a -&gt; &lt; get : 'a; set : 'a -&gt; unit &gt; = &lt;fun&gt;
</FONT></PRE>
On the other hand, a class for polymorphic references must explicitly
list the type parameters in its declaration. Class type parameters are
always listed between <TT>[</TT> and <TT>]</TT>. The type parameters must also be
bound somewhere in the class body by a type constraint.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] ref x_init = 
   object 
     val mutable x = (x_init : 'a)
     method get = x
     method set y = x &lt;- y
   end;;
</FONT><FONT COLOR=maroon>class ['a] ref :
  'a -&gt; object val mutable x : 'a method get : 'a method set : 'a -&gt; unit end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let r = new ref 1 in r#set 2; (r#get);;
</FONT>- : int = 2
</FONT></PRE>
The type parameter in the declaration may actually be constrained in the
body of the class definition. In the class type, the actual value of
the type parameter is displayed in the <TT>constraint</TT> clause. 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] ref_succ (x_init:'a) = 
   object
     val mutable x = x_init + 1
     method get = x
     method set y = x &lt;- y
   end;;
</FONT><FONT COLOR=maroon>class ['a] ref_succ :
  'a -&gt;
  object
    constraint 'a = int
    val mutable x : int
    method get : int
    method set : int -&gt; unit
  end
</FONT></PRE>
Let us consider a more complex example: define a circle, whose center
may be any kind of point. We put an additional type
constraint in method <TT>move</TT>, since no free variables must remain 
unaccounted for by the class type parameters.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] circle (c : 'a) =
   object 
     val mutable center = c
     method center = center
     method set_center c = center &lt;- c
     method move = (center#move : int -&gt; unit)
   end;;
</FONT><FONT COLOR=maroon>class ['a] circle :
  'a -&gt;
  object
    constraint 'a = &lt; move : int -&gt; unit; .. &gt;
    val mutable center : 'a
    method center : 'a
    method move : int -&gt; unit
    method set_center : 'a -&gt; unit
  end
</FONT></PRE>
An alternate definition of <TT>circle</TT>, using a <TT>constraint</TT> clause in
the class definition, is shown below. The type <TT>#point</TT> used below in
the <TT>constraint</TT> clause is an abbreviation produced by the definition
of class <TT>point</TT>. This abbreviation unifies with the type of any
object belonging to a subclass of class <TT>point</TT>. It actually expands to
<TT>&lt; get_x : int; move : int -&gt; unit; .. &gt;</TT>. This leads to the following
alternate definition of <TT>circle</TT>, which has slightly stronger
constraints on its argument, as we now expect <TT>center</TT> to have a
method <TT>get_x</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] circle (c : 'a) =
   object 
     constraint 'a = #point
     val mutable center = c
     method center = center
     method set_center c = center &lt;- c
     method move = center#move
   end;;
</FONT><FONT COLOR=maroon>class ['a] circle :
  'a -&gt;
  object
    constraint 'a = #point
    val mutable center : 'a
    method center : 'a
    method move : int -&gt; unit
    method set_center : 'a -&gt; unit
  end
</FONT></PRE>
The class <TT>colored_circle</TT> is a specialized version of class
<TT>circle</TT> that requires the type of the center to unify with
<TT>#colored_point</TT>, and adds a method <TT>color</TT>. Note that when specializing a
parameterized class, the instance of type parameter must always be
explicitly given. It is again written between <TT>[</TT> and <TT>]</TT>. 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] colored_circle c =
   object
     constraint 'a = #colored_point
     inherit ['a] circle c
     method color = center#color
   end;;
</FONT><FONT COLOR=maroon>class ['a] colored_circle :
  'a -&gt;
  object
    constraint 'a = #colored_point
    val mutable center : 'a
    method center : 'a
    method color : string
    method move : int -&gt; unit
    method set_center : 'a -&gt; unit
  end
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc29">3.11</A>&nbsp;&nbsp;Polymorphic methods</H2>

<A NAME="ss:polymorphic-methods"></A>
While parameterized classes may be polymorphic in their contents, they
are not enough to allow polymorphism of method use.<BR>
<BR>
A classical example is defining an iterator.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>List.fold_left;;
</FONT><FONT COLOR=maroon>- : ('a -&gt; 'b -&gt; 'a) -&gt; 'a -&gt; 'b list -&gt; 'a = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] intlist (l : int list) =
   object
     method empty = (l = [])
     method fold f (accu : 'a) = List.fold_left f accu l
   end;;
</FONT>class ['a] intlist :
  int list -&gt;
  object method empty : bool method fold : ('a -&gt; int -&gt; 'a) -&gt; 'a -&gt; 'a end
</FONT></PRE>
At first look, we seem to have a polymorphic iterator, however this
does not work in practice.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let l = new intlist [1; 2; 3];;
</FONT><FONT COLOR=maroon>val l : '_a intlist = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>l#fold (fun x y -&gt; x+y) 0;;
</FONT>- : int = 6
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>l;;
</FONT>- : int intlist = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>l#fold (fun s x -&gt; <U>s</U> ^ string_of_int x ^ " ") "";;
</FONT>This expression has type int but is here used with type string
</FONT></PRE>
Our iterator works, as shows its first use for summation. However,
since objects themselves are not polymorphic (only their constructors
are), using the <TT>fold</TT> method fixes its type for this individual object.
Our next attempt to use it as a string iterator fails.<BR>
<BR>
The problem here is that quantification was wrongly located: this is
not the class we want to be polymorphic, but the <TT>fold</TT> method.
This can be achieved by giving an explicitly polymorphic type in the
method definition.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class intlist (l : int list) =
   object
     method empty = (l = [])
     method fold : 'a. ('a -&gt; int -&gt; 'a) -&gt; 'a -&gt; 'a =
       fun f accu -&gt; List.fold_left f accu l
   end;;
</FONT><FONT COLOR=maroon>class intlist :
  int list -&gt;
  object method empty : bool method fold : ('a -&gt; int -&gt; 'a) -&gt; 'a -&gt; 'a end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let l = new intlist [1; 2; 3];;
</FONT>val l : intlist = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>l#fold (fun x y -&gt; x+y) 0;;
</FONT>- : int = 6
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>l#fold (fun s x -&gt; s ^ string_of_int x ^ " ") "";;
</FONT>- : string = "1 2 3 "
</FONT></PRE>
As you can see in the class type shown by the compiler, while
polymorphic method types must be fully explicit in class definitions
(appearing immediately after the method name), quantified type
variables can be left implicit in class descriptions.
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
Why require types
to be explicit? The problem is that <TT>(int -&gt; int -&gt; int) -&gt; int -&gt; int</TT> would also be a valid type for <TT>fold</TT>, and it happens to be
incompatible with the polymorphic type we gave (automatic
instantiation only works for toplevel types variables, not for inner
quantifiers, where it becomes an undecidable problem.) So the compiler
cannot choose between those two types, and must be helped.<BR>
</div>
<BR>
However, the type can be completely omitted in the class definition if
it is already known, through inheritance or type constraints on self.
Here is an example of method overriding.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class intlist_rev l =
   object
     inherit intlist l
     method fold f accu = List.fold_left f accu (List.rev l)
   end;;
</FONT></PRE>
The following idiom separates description and definition.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class type ['a] iterator =
   object method fold : ('b -&gt; 'a -&gt; 'b) -&gt; 'b -&gt; 'b end;;
&nbsp;
 class intlist l =
   object (self : int #iterator)
     method empty = (l = [])
     method fold f accu = List.fold_left f accu l
   end;;
</FONT></PRE>
Note here the <TT>(self : int #iterator)</TT> idiom, which ensures that this
object implements the interface <TT>iterator</TT>.<BR>
<BR>
Polymorphic methods are called in exactly the same way as normal
methods, but you should be aware of some limitations of type
inference. Namely, a polymorphic method can only be called if its
type is known at the call site. Otherwise, the method will be assumed
to be monomorphic, and given an incompatible type.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let sum lst = lst#fold (fun x y -&gt; x+y) 0;;
</FONT><FONT COLOR=maroon>val sum : &lt; fold : (int -&gt; int -&gt; int) -&gt; int -&gt; 'a; .. &gt; -&gt; 'a = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>sum <U>l</U>;;
</FONT>This expression has type intlist but is here used with type
  &lt; fold : (int -&gt; int -&gt; int) -&gt; int -&gt; 'a; .. &gt;
Types for method fold are incompatible
</FONT></PRE>
The workaround is easy: you should put a type constraint on the
parameter.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let sum (lst : _ #iterator) = lst#fold (fun x y -&gt; x+y) 0;;
</FONT><FONT COLOR=maroon>val sum : int #iterator -&gt; int = &lt;fun&gt;
</FONT></PRE>
Of course the constraint may also be an explicit method type.
Only occurences of quantified variables are required.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let sum lst =
   (lst : &lt; fold : 'a. ('a -&gt; _ -&gt; 'a) -&gt; 'a -&gt; 'a; .. &gt;)#fold (+) 0;;
</FONT><FONT COLOR=maroon>val sum : &lt; fold : 'a. ('a -&gt; int -&gt; 'a) -&gt; 'a -&gt; 'a; .. &gt; -&gt; int = &lt;fun&gt;
</FONT></PRE>
Another use of polymorphic methods is to allow some form of implicit
subtyping in method arguments. We have already seen in section
<A HREF="#ss:inheritance">3.8</A> how some functions may be polymorphic in the
class of their argument. This can be extended to methods.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class type point0 = object method get_x : int end;;
</FONT><FONT COLOR=maroon>class type point0 = object method get_x : int end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class distance_point x =
   object
     inherit point x
     method distance : 'a. (#point0 as 'a) -&gt; int =
       fun other -&gt; abs (other#get_x - x)
   end;;
</FONT>class distance_point :
  int -&gt;
  object
    val mutable x : int
    method distance : #point0 -&gt; int
    method get_offset : int
    method get_x : int
    method move : int -&gt; unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new distance_point 3 in
 (p#distance (new point 8), p#distance (new colored_point 1 "blue"));;
</FONT>- : int * int = (5, 2)
</FONT></PRE>
Note here the special syntax <TT>(#point0 as 'a)</TT> we have to use to
quantify the extensible part of <TT>#point0</TT>. As for the variable binder,
it can be omitted in class specifications. If you want polymorphism
inside object field it must be quantified independently.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class multi_poly =
   object
     method m1 : 'a. (&lt; n1 : 'b. 'b -&gt; 'b; .. &gt; as 'a) -&gt; _ =
       fun o -&gt; o#n1 true, o#n1 "hello"
     method m2 : 'a 'b. (&lt; n2 : 'b -&gt; bool; .. &gt; as 'a) -&gt; 'b -&gt; _ =
       fun o x -&gt; o#n2 x
   end;;
</FONT><FONT COLOR=maroon>class multi_poly :
  object
    method m1 : &lt; n1 : 'a. 'a -&gt; 'a; .. &gt; -&gt; bool * string
    method m2 : &lt; n2 : 'b -&gt; bool; .. &gt; -&gt; 'b -&gt; bool
  end
</FONT></PRE>
In method <TT>m1</TT>, <TT>o</TT> must be an object with at least a method <TT>n1</TT>,
itself polymorphic. In method <TT>m2</TT>, the argument of <TT>n2</TT> and <TT>x</TT> must
have the same type, which is quantified at the same level as <TT>'a</TT>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc30">3.12</A>&nbsp;&nbsp;Using coercions</H2>

<A NAME="ss:using-coercions"></A>
Subtyping is never implicit. There are, however, two ways to perform
subtyping. The most general construction is fully explicit: both the
domain and the codomain of the type coercion must be given.<BR>
<BR>
We have seen that points and colored points have incompatible types.
For instance, they cannot be mixed in the same list. However, a
colored point can be coerced to a point, hiding its <TT>color</TT> method:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let colored_point_to_point cp = (cp : colored_point :&gt; point);;
</FONT><FONT COLOR=maroon>val colored_point_to_point : colored_point -&gt; point = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new point 3 and q = new colored_point 4 "blue";;
</FONT>val p : point = &lt;obj&gt;
val q : colored_point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let l = [p; (colored_point_to_point q)];;
</FONT>val l : point list = [&lt;obj&gt;; &lt;obj&gt;]
</FONT></PRE>
An object of type <TT>t</TT> can be seen as an object of type <TT>t'</TT> 
only if <TT>t</TT> is a subtype of <TT>t'</TT>. For instance, a point cannot be
seen as a colored point. 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue><U>(p : point :&gt; colored_point)</U>;;
</FONT><FONT COLOR=maroon>Type point = &lt; get_offset : int; get_x : int; move : int -&gt; unit &gt;
is not a subtype of type
  colored_point =
    &lt; color : string; get_offset : int; get_x : int; move : int -&gt; unit &gt; 
</FONT></PRE>
Indeed, narrowing coercions would be unsafe, and could only be combined with
a type case, possibly raising a runtime error. However, there is no such
operation available in the language. <BR>
<BR>
Be aware that subtyping and inheritance are not related. Inheritance is a
syntactic relation between classes while subtyping is a semantic relation
between types. For instance, the class of colored points could have been
defined directly, without inheriting from the class of points; the type of
colored points would remain unchanged and thus still be a subtype of
points.
<BR>
<BR>
The domain of a coercion can usually be omitted. For instance, one can
define:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let to_point cp = (cp :&gt; point);;
</FONT><FONT COLOR=maroon>val to_point : #point -&gt; point = &lt;fun&gt;
</FONT></PRE>
In this case, the function <TT>colored_point_to_point</TT> is an instance of the 
function <TT>to_point</TT>. This is not always true, however. The fully
explicit coercion is more precise and is sometimes unavoidable. 
Consider, for example, the following class:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class c0 = object method m = {&lt; &gt;} method n = 0 end;;
</FONT><FONT COLOR=maroon>class c0 : object ('a) method m : 'a method n : int end
</FONT></PRE>
The object type <TT>c0</TT> is an abbreviation for <TT>&lt;m : 'a; n : int&gt; as 'a</TT>. 
Consider now the type declaration:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class type c1 =  object method m : c1 end;;
</FONT><FONT COLOR=maroon>class type c1 = object method m : c1 end
</FONT></PRE>
The object type <TT>c1</TT> is an abbreviation for the type <TT>&lt;m : 'a&gt; as 'a</TT>. 
The coercion from an object of type <TT>c0</TT> to an object of type <TT>c1</TT> is
correct: 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>fun (x:c0) -&gt; (x : c0 :&gt; c1);;
</FONT><FONT COLOR=maroon>- : c0 -&gt; c1 = &lt;fun&gt;
</FONT></PRE>
However, the domain of the coercion cannot be omitted here: 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>fun (x:c0) -&gt; (<U>x</U> :&gt; c1);;
</FONT><FONT COLOR=maroon>This expression cannot be coerced to type c1 = &lt; m : c1 &gt;; it has type
  c0 = &lt; m : c0; n : int &gt;
but is here used with type &lt; m : #c1 as 'a; .. &gt;
Type c0 = &lt; m : c0; n : int &gt; is not compatible with type 'a = &lt; m : c1; .. &gt; 
Type c0 = &lt; m : c0; n : int &gt; is not compatible with type c1 = &lt; m : c1 &gt; 
Only the first object type has a method n.
This simple coercion was not fully general. Consider using a double coercion.
</FONT></PRE>
The solution is to use the explicit form. 
Sometimes, a change in the class-type definition can also solve the problem
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class type c2 =  object ('a) method m : 'a end;;
</FONT><FONT COLOR=maroon>class type c2 = object ('a) method m : 'a end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>fun (x:c0) -&gt; (x :&gt; c2);;
</FONT>- : c0 -&gt; c2 = &lt;fun&gt;
</FONT></PRE>
While class types <TT>c1</TT> and <TT>c2</TT> are different, both object types
<TT>c1</TT> and <TT>c2</TT> expand to the same object type (same method names and types).
Yet, when the domain of a coercion is left implicit and its co-domain
is an abbreviation of a known class type, then the class type, rather
than the object type, is used to derive the coercion function. This
allows to leave the domain implicit in most cases when coercing form a
subclass to its superclass.
The type of a coercion can always be seen as below: 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let to_c1 x = (x :&gt; c1);;
</FONT><FONT COLOR=maroon>val to_c1 : &lt; m : #c1; .. &gt; -&gt; c1 = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let to_c2 x = (x :&gt; c2);;
</FONT>val to_c2 : #c2 -&gt; c2 = &lt;fun&gt;
</FONT></PRE>
Note the difference between the two coercions: in the second case, the type
<TT>#c2 = &lt; m : 'a; .. &gt; as 'a</TT> is polymorphically recursive (according
to the explicit recursion in the class type of <TT>c2</TT>); hence the
success of applying this coercion to an object of class <TT>c0</TT>.
On the other hand, in the first case, <TT>c1</TT> was only expanded and
unrolled twice to obtain <TT>&lt; m : &lt; m : c1; .. &gt;; .. &gt;</TT> (remember <TT>#c1 = &lt; m : c1; .. &gt;</TT>), without introducing recursion.
You may also note that the type of <TT>to_c2</TT> is <TT>#c2 -&gt; c2</TT> while
the type of <TT>to_c1</TT> is more general than <TT>#c1 -&gt; c1</TT>. This is not always true,
since there are class types for which some instances of <TT>#c</TT> are not subtypes
of <TT>c</TT>, as explained in section&nbsp;<A HREF="#ss:binary-methods">3.16</A>. Yet, for
parameterless classes the coercion <TT>(_ :&gt; c)</TT> is always more general than
<TT>(_ : #c :&gt; c)</TT>.
<BR>
<BR>
A common problem may occur when one tries to define a coercion to a
class <TT>c</TT> while defining class <TT>c</TT>. The problem is due to the type
abbreviation not being completely defined yet, and so its subtypes are not
clearly known. Then, a coercion <TT>(_ :&gt; c)</TT> or <TT>(_ : #c :&gt; c)</TT> is taken to be 
the identity function, as in
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>function x -&gt; (x :&gt; 'a);;
</FONT><FONT COLOR=maroon>- : 'a -&gt; 'a = &lt;fun&gt;
</FONT></PRE>
As a consequence, if the coercion is applied to <TT>self</TT>, as in the
following example, the type of <TT>self</TT> is unified with the closed type
<TT>c</TT> (a closed object type is an object type without ellipsis). This
would constrain the type of self be closed and is thus rejected.
Indeed, the type of self cannot be closed: this would prevent any
further extension of the class. Therefore, a type error is generated
when the unification of this type with another type would result in a
closed object type.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class c = object method m = 1 end
 and d = object (self)
   inherit c
   method n = 2
   method as_c = (<U>self</U> :&gt; c)
 end;;
</FONT><FONT COLOR=maroon>This expression cannot be coerced to type c = &lt; m : int &gt;; it has type
  &lt; as_c : c; m : int; n : int; .. &gt;
but is here used with type c
Self type cannot be unified with a closed object type
</FONT></PRE>
However, the most common instance of this problem, coercing self to
its current class, is detected as a special case by the type checker,
and properly typed.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class c = object (self) method m = (self :&gt; c) end;;
</FONT><FONT COLOR=maroon>class c : object method m : c end
</FONT></PRE>
This allows the following idiom, keeping a list of all objects
belonging to a class or its subclasses:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let all_c = ref [];;
</FONT><FONT COLOR=maroon>val all_c : '_a list ref = {contents = []}
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class c (m : int) =
   object (self)
     method m = m
     initializer all_c := (self :&gt; c) :: !all_c
   end;;
</FONT>class c : int -&gt; object method m : int end
</FONT></PRE>
This idiom can in turn be used to retrieve an object whose type has
been weakened:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let rec lookup_obj obj = function [] -&gt; raise Not_found
   | obj' :: l -&gt;
      if (obj :&gt; &lt; &gt;) = (obj' :&gt; &lt; &gt;) then obj' else lookup_obj obj l ;;
</FONT><FONT COLOR=maroon>val lookup_obj : &lt; .. &gt; -&gt; (&lt; .. &gt; as 'a) list -&gt; 'a = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let lookup_c obj = lookup_obj obj !all_c;;
</FONT>val lookup_c : &lt; .. &gt; -&gt; &lt; m : int &gt; = &lt;fun&gt;
</FONT></PRE>
The type <TT>&lt; m : int &gt;</TT> we see here is just the expansion of <TT>c</TT>, due
to the use of a reference; we have succeeded in getting back an object
of type <TT>c</TT>.<BR>
<BR>
<BR>
The previous coercion problem can often be avoided by first
defining the abbreviation, using a class type:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class type c' = object method m : int end;;
</FONT><FONT COLOR=maroon>class type c' = object method m : int end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class c : c' = object method m = 1 end
 and d = object (self)
   inherit c
   method n = 2
   method as_c = (self :&gt; c')
 end;;
</FONT>class c : c'
and d : object method as_c : c' method m : int method n : int end
</FONT></PRE>
It is also possible to use a virtual class. Inheriting from this class
simultaneously allows to enforce all methods of <TT>c</TT> to have the same
type as the methods of <TT>c'</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class virtual c' = object method virtual m : int end;;
</FONT><FONT COLOR=maroon>class virtual c' : object method virtual m : int end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class c = object (self) inherit c' method m = 1 end;;
</FONT>class c : object method m : int end
</FONT></PRE>
One could think of defining the type abbreviation directly:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>type c' = &lt;m : int&gt;;;
</FONT></PRE>
However, the abbreviation <TT>#c'</TT> cannot be defined directly in a similar way.
It can only be defined by a class or a class-type definition. 
This is because <TT>#</TT> sharp abbreviations carry an implicit anonymous
variable <TT>..</TT> that cannot be explicitly named.
The closer you get to it is:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>type 'a c'_class = 'a constraint 'a = &lt; m : int; .. &gt;;;
</FONT></PRE>
with an extra type variable capturing the open object type.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc31">3.13</A>&nbsp;&nbsp;Functional objects</H2>

<A NAME="ss:functional-objects"></A>
It is possible to write a version of class <TT>point</TT> without assignments
on the instance variables. The construct <TT>{&lt; ... &gt;}</TT> returns a copy of
&#8220;self&#8221; (that is, the current object), possibly changing the value of
some instance variables.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class functional_point y =
   object 
     val x = y
     method get_x = x
     method move d = {&lt; x = x + d &gt;}
   end;;
</FONT><FONT COLOR=maroon>class functional_point :
  int -&gt;
  object ('a) val x : int method get_x : int method move : int -&gt; 'a end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new functional_point 7;;
</FONT>val p : functional_point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#get_x;;
</FONT>- : int = 7
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>(p#move 3)#get_x;;
</FONT>- : int = 10
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p#get_x;;
</FONT>- : int = 7
</FONT></PRE>
Note that the type abbreviation <TT>functional_point</TT> is recursive, which can
be seen in the class type of <TT>functional_point</TT>: the type of self is <TT>'a</TT>
and <TT>'a</TT> appears inside the type of the method <TT>move</TT>.<BR>
<BR>
The above definition of <TT>functional_point</TT> is not equivalent
to the following: 
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class bad_functional_point y =
   object 
     val x = y
     method get_x = x
     method move d = new bad_functional_point (x+d)
   end;;
</FONT><FONT COLOR=maroon>class bad_functional_point :
  int -&gt;
  object
    val x : int
    method get_x : int
    method move : int -&gt; bad_functional_point
  end
</FONT></PRE>
While objects of either class will behave the same, objects of their
subclasses will be different. In a subclass of the latter, the method
<TT>move</TT> will
keep returning an object of the parent class. On the contrary, in a
subclass of the former, the method <TT>move</TT> will return an object of the
subclass.<BR>
<BR>
Functional update is often used in conjunction with binary methods
as illustrated in section <A HREF="manual007.html#module:string">5.2.1</A>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc32">3.14</A>&nbsp;&nbsp;Cloning objects</H2>

<A NAME="ss:cloning-objects"></A>
Objects can also be cloned, whether they are functional or imperative.
The library function <TT>Oo.copy</TT> makes a shallow copy of an object. That is, 
it returns an object that is equal to the previous one. The 
instance variables have been copied but their contents are shared.
Assigning a new value to an instance variable of the copy (using a method
call) will not affect instance variables of the original, and conversely. 
A deeper assignment (for example if the instance variable if a reference cell) 
will of course affect both the original and the copy. <BR>
<BR>
The type of <TT>Oo.copy</TT> is the following:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>Oo.copy;;
</FONT><FONT COLOR=maroon>- : (&lt; .. &gt; as 'a) -&gt; 'a = &lt;fun&gt;
</FONT></PRE>
The keyword <TT>as</TT> in that type binds the type variable <TT>'a</TT> to
the object type <TT>&lt; .. &gt;</TT>. Therefore, <TT>Oo.copy</TT> takes an object with
any methods (represented by the ellipsis), and returns an object of
the same type. The type of <TT>Oo.copy</TT> is different from type <TT>&lt; .. &gt; -&gt; &lt; .. &gt;</TT> as each ellipsis represents a different set of methods.
Ellipsis actually behaves as a type variable.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new point 5;;
</FONT><FONT COLOR=maroon>val p : point = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let q = Oo.copy p;;
</FONT>val q : &lt; get_offset : int; get_x : int; move : int -&gt; unit &gt; = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>q#move 7; (p#get_x, q#get_x);;
</FONT>- : int * int = (5, 12)
</FONT></PRE>
In fact, <TT>Oo.copy p</TT> will behave as <TT>p#copy</TT> assuming that a public
method <TT>copy</TT> with body <TT>{&lt; &gt;}</TT> has been defined in the class of <TT>p</TT>.<BR>
<BR>
Objects can be compared using the generic comparison functions <TT>=</TT> and <TT>&lt;&gt;</TT>.
Two objects are equal if and only if they are physically equal. In
particular, an object and its copy are not equal.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let q = Oo.copy p;;
</FONT><FONT COLOR=maroon>val q : &lt; get_offset : int; get_x : int; move : int -&gt; unit &gt; = &lt;obj&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>p = q, p = p;;
</FONT>- : bool * bool = (false, true)
</FONT></PRE>
Other generic comparissons such as (<TT>&lt;</TT>, <TT>&lt;=</TT>,...) can also be used on objects. The
relation <TT>&lt;</TT> defines an unspecified but strict ordering on objets. The
ordering relationship between two objects is fixed once for all after the
two objects have been created and it is not affected by mutation of fields.<BR>
<BR>
Cloning and override have a non empty intersection.
They are interchangeable when used within an object and without 
overriding any field:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class copy =
   object
     method copy = {&lt; &gt;}
   end;;
</FONT><FONT COLOR=maroon>class copy : object ('a) method copy : 'a end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>class copy =
   object (self)
     method copy = Oo.copy self
   end;;
</FONT>class copy : object ('a) method copy : 'a end
</FONT></PRE>
Only the override can be used to actually override fields, and 
only the <TT>Oo.copy</TT> primitive can be used externally. <BR>
<BR>
Cloning can also be used to provide facilities for saving and
restoring the state of objects.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class backup = 
   object (self : 'mytype)
     val mutable copy = None
     method save = copy &lt;- Some {&lt; copy = None &gt;}
     method restore = match copy with Some x -&gt; x | None -&gt; self
   end;;
</FONT><FONT COLOR=maroon>class backup :
  object ('a)
    val mutable copy : 'a option
    method restore : 'a
    method save : unit
  end
</FONT></PRE>
The above definition will only backup one level. 
The backup facility can be added to any class using multiple inheritance.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] backup_ref x = object inherit ['a] ref x inherit backup end;;
</FONT><FONT COLOR=maroon>class ['a] backup_ref :
  'a -&gt;
  object ('b)
    val mutable copy : 'b option
    val mutable x : 'a
    method get : 'a
    method restore : 'b
    method save : unit
    method set : 'a -&gt; unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);;
</FONT>val get : (&lt; get : 'b; restore : 'a; .. &gt; as 'a) -&gt; int -&gt; 'b = &lt;fun&gt;
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new backup_ref 0  in
 p # save; p # set 1; p # save; p # set 2; 
 [get p 0; get p 1; get p 2; get p 3; get p 4];;
</FONT>- : int list = [2; 1; 1; 1; 1]
</FONT></PRE>
A variant of backup could retain all copies. (We then add a method clear to
manually erase all copies.)
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class backup = 
   object (self : 'mytype)
     val mutable copy = None
     method save = copy &lt;- Some {&lt; &gt;}
     method restore = match copy with Some x -&gt; x | None -&gt; self
     method clear = copy &lt;- None
   end;;
</FONT><FONT COLOR=maroon>class backup :
  object ('a)
    val mutable copy : 'a option
    method clear : unit
    method restore : 'a
    method save : unit
  end
</FONT></PRE>
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class ['a] backup_ref x = object inherit ['a] ref x inherit backup end;;
</FONT><FONT COLOR=maroon>class ['a] backup_ref :
  'a -&gt;
  object ('b)
    val mutable copy : 'b option
    val mutable x : 'a
    method clear : unit
    method get : 'a
    method restore : 'b
    method save : unit
    method set : 'a -&gt; unit
  end
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>let p = new backup_ref 0  in
 p # save; p # set 1; p # save; p # set 2; 
 [get p 0; get p 1; get p 2; get p 3; get p 4];;
</FONT>- : int list = [2; 1; 0; 0; 0]
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc33">3.15</A>&nbsp;&nbsp;Recursive classes</H2>

<A NAME="ss:recursive-classes"></A>
Recursive classes can be used to define objects whose types are
mutually recursive.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class window =
   object 
     val mutable top_widget = (None : widget option)
     method top_widget = top_widget
   end
 and widget (w : window) =
   object
     val window = w
     method window = window
   end;;
</FONT><FONT COLOR=maroon>class window :
  object
    val mutable top_widget : widget option
    method top_widget : widget option
  end
and widget : window -&gt; object val window : window method window : window end
</FONT></PRE>
Although their types are mutually recursive, the classes <TT>widget</TT> and 
<TT>window</TT> are themselves independent. <BR>
<BR>

<H2 CLASS="section"><A NAME="htoc34">3.16</A>&nbsp;&nbsp;Binary methods</H2>

<A NAME="ss:binary-methods"></A>
A binary method is a method which takes an argument of the same type
as self. The class <TT>comparable</TT> below is a template for classes with a
binary method <TT>leq</TT> of type <TT>'a -&gt; bool</TT> where the type variable <TT>'a</TT>
is bound to the type of self. Therefore, <TT>#comparable</TT> expands to <TT>&lt; leq : 'a -&gt; bool; .. &gt; as 'a</TT>. We see here that the binder <TT>as</TT> also
allows to write recursive types.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class virtual comparable = 
   object (_ : 'a)
     method virtual leq : 'a -&gt; bool
   end;;
</FONT><FONT COLOR=maroon>class virtual comparable : object ('a) method virtual leq : 'a -&gt; bool end
</FONT></PRE>
We then define a subclass <TT>money</TT> of <TT>comparable</TT>. The class money 
simply wraps floats as comparable objects. We will extend it below with
more operations. There is a type constraint on the class parameter <TT>x</TT>
as the primitive <TT>&lt;=</TT> is a polymorphic comparison function in
Objective Caml. The <TT>inherit</TT> clause ensures that the type of objects
of this class is an instance of <TT>#comparable</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class money (x : float) =
   object
     inherit comparable
     val repr = x
     method value = repr
     method leq p = repr &lt;= p#value
   end;;
</FONT><FONT COLOR=maroon>class money :
  float -&gt;
  object ('a)
    val repr : float
    method leq : 'a -&gt; bool
    method value : float
  end
</FONT></PRE>
Note that the type <TT>money1</TT> is not a subtype of type
<TT>comparable</TT>, as the self type appears in contravariant position
in the type of method <TT>leq</TT>.
Indeed, an object <TT>m</TT> of class <TT>money</TT> has a method <TT>leq</TT>
that expects an argument of type <TT>money</TT> since it accesses
its <TT>value</TT> method. Considering <TT>m</TT> of type <TT>comparable</TT> would allow to
call method <TT>leq</TT> on <TT>m</TT> with an argument that does not have a method
<TT>value</TT>, which would be an error.<BR>
<BR>
Similarly, the type <TT>money2</TT> below is not a subtype of type <TT>money</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class money2 x =
   object   
     inherit money x
     method times k = {&lt; repr = k *. repr &gt;}
   end;;
</FONT><FONT COLOR=maroon>class money2 :
  float -&gt;
  object ('a)
    val repr : float
    method leq : 'a -&gt; bool
    method times : float -&gt; 'a
    method value : float
  end
</FONT></PRE>
It is however possible to define functions that manipulate objects of
type either <TT>money</TT> or <TT>money2</TT>: the function <TT>min</TT>
will return the minimum of any two objects whose type unifies with
<TT>#comparable</TT>. The type of <TT>min</TT> is not the same as <TT>#comparable -&gt; #comparable -&gt; #comparable</TT>, as the abbreviation <TT>#comparable</TT> hides a
type variable (an ellipsis). Each occurrence of this abbreviation
generates a new variable.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>let min (x : #comparable) y =
   if x#leq y then x else y;;
</FONT><FONT COLOR=maroon>val min : (#comparable as 'a) -&gt; 'a -&gt; 'a = &lt;fun&gt;
</FONT></PRE>
This function can be applied to objects of type <TT>money</TT>
or <TT>money2</TT>.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>(min (new money  1.3) (new money 3.1))#value;;
</FONT><FONT COLOR=maroon>- : float = 1.3
&nbsp;
<FONT COLOR=black>#</FONT><FONT COLOR=blue>(min (new money2 5.0) (new money2 3.14))#value;;
</FONT>- : float = 3.14
</FONT></PRE>
More examples of binary methods can be found in sections
<A HREF="manual007.html#module:string">5.2.1</A> and <A HREF="manual007.html#module:set">5.2.3</A>.<BR>
<BR>
Notice the use of functional update for method <TT>times</TT>. 
Writing <TT>new money2 (k *. repr)</TT> instead of <TT>{&lt; repr = k *. repr &gt;}</TT>
would not behave well with inheritance: in a subclass <TT>money3</TT> of <TT>money2</TT>
the <TT>times</TT> method would return an object of class <TT>money2</TT> but not of class
<TT>money3</TT> as would be expected. <BR>
<BR>
The class <TT>money</TT> could naturally carry another binary method. Here is a
direct definition:
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class money x =
   object (self : 'a)
     val repr = x
     method value = repr
     method print = print_float repr
     method times k = {&lt; repr = k *. x &gt;}
     method leq (p : 'a) = repr &lt;= p#value
     method plus (p : 'a) = {&lt; repr = x +. p#value &gt;}
   end;;
</FONT><FONT COLOR=maroon>class money :
  float -&gt;
  object ('a)
    val repr : float
    method leq : 'a -&gt; bool
    method plus : 'a -&gt; 'a
    method print : unit
    method times : float -&gt; 'a
    method value : float
  end
</FONT></PRE>

<H2 CLASS="section"><A NAME="htoc35">3.17</A>&nbsp;&nbsp;Friends</H2>

<A NAME="ss:friends"></A>
The above class <TT>money</TT> reveals a problem that often occurs with binary
methods. In order to interact with other objects of the same class, the
representation of <TT>money</TT> objects must be revealed, using a method such as
<TT>value</TT>. If we remove all binary methods (here <TT>plus</TT> and <TT>leq</TT>),
the representation can easily be hidden inside objects by removing the method
<TT>value</TT> as well. However, this is not possible as long as some binary
requires access to the representation on object of the same class but
different from self.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>class safe_money x =
   object (self : 'a)
     val repr = x
     method print = print_float repr
     method times k = {&lt; repr = k *. x &gt;}
   end;;
</FONT><FONT COLOR=maroon>class safe_money :
  float -&gt;
  object ('a)
    val repr : float
    method print : unit
    method times : float -&gt; 'a
  end
</FONT></PRE>
Here, the representation of the object is known only to a particular object.
To make it available to other objects of the same class, we are forced to
make it available to the whole world. However we can easily restrict the
visibility of the representation using the module system.
<PRE><FONT COLOR=black>#</FONT><FONT COLOR=blue>module type MONEY = 
   sig 
     type t
     class c : float -&gt; 
       object ('a)
         val repr : t
         method value : t
         method print : unit
         method times : float -&gt; 'a
         method leq : 'a -&gt; bool
         method plus : 'a -&gt; 'a 
       end
   end;;
&nbsp;
 module Euro : MONEY = 
   struct
     type t = float
     class c x =
       object (self : 'a)
         val repr = x
         method value = repr
         method print = print_float repr
         method times k = {&lt; repr = k *. x &gt;}
         method leq (p : 'a) = repr &lt;= p#value
         method plus (p : 'a) = {&lt; repr = x +. p#value &gt;}
       end
   end;;
</FONT></PRE>
Another example of friend functions may be found in section
<A HREF="manual007.html#module:set">5.2.3</A>. These examples occur when a group of objects (here
objects of the same class) and functions should see each others internal
representation, while their representation should be hidden from the
outside. The solution is always to define all friends in the same module,
give access to the representation and use a signature constraint to make the
representation abstract outside of the module.<BR>
<BR>

<BR>
<BR>
<HR>
<A HREF="manual004.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<A HREF="manual006.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>