* Re: [Caml-list] method name collision ?
2004-12-25 22:57 ` [Caml-list] " Jacques Garrigue
@ 2004-12-26 18:20 ` John Prevost
0 siblings, 0 replies; 3+ messages in thread
From: John Prevost @ 2004-12-26 18:20 UTC (permalink / raw)
To: caml-list
On Sun, 26 Dec 2004 07:57:48 +0900 (JST), Jacques Garrigue
<garrigue@math.nagoya-u.ac.jp> wrote (in response to
briand@aracnet.com):
> The "as drawable" doesn't mean that the methods are distinct: you can
> still call all inherited methods from the outside, and even through
> self.
> This only allows you to access the old definition of a method, if you
> want to extend it incrementally.
>
> method point ~x ~y =
> ... drawable#point ~x ~y ...
And just to make sure it's clear, the reason that the type has to
match is that *other* methods of the inherited class have to be able
to do self#point calls on the new object and work properly. Here's an
illustration:
-----
class test_1 =
object (self)
method test a = a + 1
method test_self () = self#test 5
end
class test_2 =
object
inherit test_1 as t1
method test x =
Printf.printf "Called with %d\n" x;
t1#test x
end
-----
In this example code, you can see that the inherited methods from
test_1, when they make self#... calls, use the overridden methods in
test_2. So if test_2 were allowed to change the types of the methods
in incompatible ways, there would be a problem.
If you *do* want to just use the methods from the other class, I
recommend using the following idiom:
Instead of this:
class broken =
object
inherit some_other_class as soc
method replace_and_change_type = ...
(* method pass_through_unchanged is inherited from soc *)
end
write this:
class working =
let soc = new some_other_class in
object
method replace_and_change_type = ...
method pass_through_unchanged = soc#pass_through_unchanged
end
The first one brings inheritance into play--which is important if you
want to override methods, but is not neccessary (or sufficient) in
OCaml to define a subtype. If, instead, you want to make use of the
other class's features in order to implement your class, and pass some
methods through unchanged, use the second model. If you need a
mixture of both, first extend the base class in order to override its
methods (for the base class's internal use, calling self#...), then
use the second model to provide a different interface.
Finally, I just realized that you could also do this if you want to
avoid defining more than one class:
class embrace_and_extend =
let extended_object = object
inherit class_you_want_to_extend
method override_something = ...
end in
object
... provide a different interface ...
end
It hadn't occurred to me before that the new immediate objects feature
allows you to inherit from a class when defining an immediate object.
(Although, of course, there is no way to inherit from an immediate
object further down the line.)
John.
^ permalink raw reply [flat|nested] 3+ messages in thread