To be honest, I don't know much about OCaml's object system. The following snippet illustrates my problem:
class foo =
object (o)
method foo1 y =
print_endline "foo1";
o#foo2 (y - 1)
method foo2 y =
print_endline "foo2";
if y > 0 then o#foo2 y else print_endline "end"
end
class bar =
object (o : 'self_type)
inherit foo as super
method foo2 y =
print_endline "bar2";
if y > 0 then super#foo1 y else print_endline "endbar"
end
let _ = (new bar)#foo2 3
When executed, the snippet produces the following output:
bar2
foo1
bar2
foo1
bar2
endbar
, showing that the superclass method foo1 (called via super#foo1) executes the overriden method foo2 from the subclass. I would instead have expected it to call the method foo2 from the superclass, as it is called via super.
Is it possible to achieve this behaviour, i.e. have a superclass method call only other superclass methods even if they are overriden in a subclass?
I'm not 100% sure on this, but I'm pretty sure you can't. In OCaml inheritance and subtyping are two different concepts. A class can be a subtype of another type without inheritance. All inheritance does is pull in the methods from the inherited class.
Polymorphism is achieved via structural typing, so your call to
foo2
calls the method inbar
becausebar
has implementedfoo2
and NOT becausebar
inherits fromfoo
(as apposed to say, C++, wherebar#foo2
is called due to a virtual function table look up).That said, OCaml does provide you with a way to distinguish between overridden methods and inherited methods using the
inherit...as...
syntax. Inbar
from your example,o#foo1
andsuper#foo1
are the same method (sincebar
doesn't implementfoo1
) whereaso#foo2
andsuper#foo2
are different methods. Despite this, I don't think there is anyway for the inherited class to know that it has been inherited and distinguish between it's methods and the overridden methods. There might be some syntax for that but I highly doubt it due to the fact that inheritance and polymorphism are independent concepts.