something "weird" about polymorphism

downs default_357-line at yahoo.de
Sun Nov 15 11:57:22 PST 2009


funog wrote:
> The following code :
> 
> ------------------
> import std.stdio;
> class A {
>     void foo(A a) {
>         writefln("A");
>     }
> }
> 
> class B : A {
>     void foo(B b) {
>         writefln("B");
>     }
> }
> 
> void main() {
>     B b = new B;
>     A a = b;
>     assert(a is b);
>     b.foo(b);
>     a.foo(b);
> }
> --------------
> outputs:
> B
> A
> 
> 
> This is understandable as B.foo doesn't actually overrides A.foo. But
> somehow it's weird to get different outputs while "a" and "b" are
> basically the same object. Has anyone else encountered this problem in
> real life? Will C+++, java act the same way?
> 

The behavior here is entirely correct and, in fact, could not happen any other way.

The only improvement would be disallowing declaring methods that shadow but don't override methods in the super class.

The inheritance contract that B enters when it inherits from A states that its foo will take any object of type A. Remember: parameters generalize, results specialize. B's foo _cannot_ override A's foo because that would mean you could not use a B in all situations you could use an A, which breaks polymorphism completely.


More information about the Digitalmars-d-learn mailing list