Polymorphism

Polymorphism is an object-oriented programming feature related to inheritance. It consist in that some property or method has the same signature across an hierarchy but its implementation may change, meaning it has an expected behavior, but the way this is achieved may vary depending on more concrete requirements.

When some derived class changes some ancestor's property or method implementation, this is an override.

jOOPL makes polymorphism easy, since any class property or method is overridable, meaning that there is a single requirement: use the same member name in order to be able to override the parent's implementation.

A sample of polymorphism with inheritance sample would be:

$namespace.register("jOOPL.Samples", function () {
    this.A = $def({
        $constructor: function (args) {
            this.$_.name = args.Name;
        },
        $members: {
            SomeMethod: function () {
                document.write(this.$_.name);
            }
        }
    });

    this.A = $def({
        $constructor: function (args) {
            this.$base.$ctor(args);
        },
        $members: {
            SomeMethod: function () {
                document.write("Got overridden!");
            }
        },
        $extends: this.A
    });

    var someB = new this.B();
    someB.SomeMethod();
});

Another case would be that the overridden method should call its base implementation too, which is achieved by using $base keyword (see keywords):

SomeMethod: function() {
              this.$base.SomeMethod();
              document.write("Got overridden!");
}

Finally, there's another use case of polymorphism: some method in a base class needs to call the most specialized version of some other method. jOOPL does it by using this.$_.$derived special field/keyword found in any object:

$namespace.register("jOOPL.Samples", function () {
    this.A = $def({
        $constructor: function () { },
        $members: {
            methodX: function () {
                // This sentence will not call the current class MethodY but the most derived version, if class A
                // is inherited by some other class.
                this.$_.$derived.methodY();
            },
            methodY: function () {
                // Class A is inherited by some other one and this method is overriden.
            }
        }
    });
});

Last edited Apr 6, 2013 at 2:20 PM by MFidemraizer, version 12

Comments

No comments yet.