Protected variable vs protected function

Hi,

When extending a class, I can override a protected function of the base class, and other functions of the base class will then use the function from my derived class.

class TestSlave extends TestMaster {
    protected function printInternal() {
        System.println( "Slave" );
    }
    public function initialize() {
        TestMaster.initialize();
    }
}

class TestMaster {
    protected function printInternal() {
        System.println( "Master" );
    }
    public function print() {
        printInternal();
    }
}

However this seems to work only for functions. For member variables, I have to declare them public for this to work, like in the example below. If I'd declare _text as protected in this example, the compiler will tell me "Attempting to override protected variable from a parent class.".

class TestSlave extends TestMaster {
    var _text = "Slave";
    public function initialize() {
        TestMaster.initialize();
    }
}

class TestMaster {
    var _text = "Master";
    public function print() {
        System.println( _text );
    }
}

Is there any sense behind this difference between functions and variables? Can I achieve this for a variable without making it public?

  • Redeclaring a variable in the child class is not like overriding a method.

    Yeah this is true for most languages other Monkey C, like Java. Kotlin does allow you to override member variables.

    The real question - as always - is why is Monkey C different?

  • "Attempting to override protected variable from a parent class."

    Also, not to state the obvious or beat the topic into the ground, but the error message itself implies that it is possible to override a variable that isn't protected (i.e. one that's public). (Aside from the fact that overriding a public member variable is proven to work in monkey c)

    If Monkey C was supposed to act just like java (member variables are not overridden), then this wouldn't be an error message at all.

    For example, the equivalent code in java doesn't produce an error message, it just acts like the member variable wasn't overridden at all (because that isn't supported in java).