#2772 Overriding Methods with Fields

SlimerDude Sat 21 Sep

I've always liked the idea of overriding methods with fields, but there's something funky going on during ctor initialisation.

With normal method overriding, all is fine:

class SuperClass {
    virtual Str someValue() { "Default Value" }

    new make() {
        echo(someValue)
    }
}

class SubClass1 : SuperClass {
    override Str someValue() { "Overridden Value" }
}

s := SubClass1()  // --> "Overridden Value"

But with field overriding:

class SubClass2 : SuperClass {
    override Str someValue := "Overridden Value"
}

s := SubClass2()  // --> null

I can see how getting the initialisation ordered correctly can be tricky, but it's something to be aware of given classes like connExt::ConnModel heavily reference their virtual methods in their ctor.

brian Sat 21 Sep

Its pretty much the same as Java - your constructor can call virtual methods, however the subclass constructor is run after the base class constructor (which is typically when subclasses set their fields). The only difference is Fantom lets you treat fields as virtual methods.

Login or Signup to reply.