Dynamic Binding and Polymorphism

I have an issue with inheritance. If I create a subclass object and call an overloaded variable/method the master class’ variable/method is used instead of the one of subclass. This behaviour is called static binding. By default dynamic binding is enabled in most script languages as long as static binding is not explicit definied.

Monoscript/Unitscript uses static binding, I don’t know why but I’m searching for a workaround…

class Animal
{
	static var desc : String = "I'm an animal";
}
class Bird extends Animal
{
	static var desc : String = "I'm a bird";
}

Anywhere in the code, I want “I’m a bird” as result!

var bird : Animal = new Bird();
Debug.Log(bird.desc);

→ Runs and prints: “I’m an animal”

// Another try

var bird : Bird = new Bird();
Debug.Log(bird.desc);

→ Debug Error BCE0004: Ambiguous reference ‘desc’: Bird.desc, Animal.desc.

All classes in Unity are precompiled, so I came across a note that you normally shouldn’t define any constructors in MonoBehaviours. That lead me to the idea defining a constructor defining the inherited variables on instantiation.

JS (not tested):

public class Animal
{
    public var desc : String = "I'm an animal";
}

public class Bird extends Animal
{
    public Bird()
    {
        desc = "I'm a bird";
    }
}

C# (tested):

public class Animal
{
    public string desc = "I'm an animal";
}

public class Bird : Animal
{
    public Bird()
    {
        desc = "I'm a bird";
    }
}

And it works… looks like the effort to rewrite the classes was close to obsolete :frowning:

According to this you have to use the virtual keyword, like

class Animal
{
    virtual static var desc : String = "I'm an animal";
}
class Bird extends Animal
{
    static var desc : String = "I'm a bird";
}

should work, but I’m not too sure about the connection between static and virtual stuff… Been writing in C# from beginnig :wink: