Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionScript Property - Public Getter, Protected Setter

Is it possible to have a property with a public getter and protected setter?

I have the following code:

public class Mob extends Sprite {
    // snip

    private var _health:Number; // tried making this protected, didn't work
    public function get health():Number { return _health; }
    protected function set health(value:Number):void {
        _health = value;
    }

    // snip

    public function takeDamage(amount:Number, type:DamageType, ... additionalAmountAndTypePairs):void {
        var dmg:Number = 0;
        // snip
        var h:Number = this.health; // 1178: Attempted access of inaccessible property health through a reference with static type components.mobs:Mob.
        this.health = h - dmg; // 1059: Property is read-only.
    }
}

I did have this.health -= dmg; but I split it out to get more details on the compiler errors.

I don't understand how the property would be considered read-only within the same class. I also don't understand how it's inaccessible.

If I make the backing field, getter, and setter all protected, it compiles but it's not the result I want; I need health to be readable externally.

like image 828
Olson.dev Avatar asked Feb 24 '23 00:02

Olson.dev


1 Answers

No, accessors have to have the same privilege levels as each other. You can have your public get set functions, then have a protected setHealth, getHealth function pair. You could reverse it if you wish, but the key point is that you have one set of methods to access at a public privilege and another to access at a protected privilege level.

like image 125
Black Dynamite Avatar answered Mar 09 '23 07:03

Black Dynamite