I am trying to set a variable whose setter is private in the constructor of the same class, but compiler keeps hitting me on the head with:
1059 Property is readonly
1178: Attempted access of inaccessible property gesamtBetrag through a reference with static type ImmoObject.
package
{
public class Huhu
{
private var _prop1:int;
public function Huhu()
{
prop1 = 24;
}
public function get prop1():int
{
return _prop1;
}
private function set prop1(value:int):void
{
_prop1 = value;
}
}
}
Am I missing something here?
As stated, you cannot have a private
setter and a public
getter. The access modifier must be the same for getter and setter.
What you can do is only have a public
getter and from within the class constructor or elsewhere you set the private
variable directly:
class Foo {
private var _prop:int;
public function Foo() {
_prop = 24;
}
public function get prop():int { return _prop; }
}
(Note that in this case you could actually just initialize the private variable with a value, ex private _prop:int = 24
.)
You could also expose other means of changing the private variable, such as a function or a setter with a different name:
class Foo {
private var _prop:int;
public function get prop():int { return _prop; }
protected function setProp(prop:int):void {
_prop = prop;
}
protected function set propValue(value:int):int {
_prop = value;
}
}
Edit: To be clear, access types must match for getter/setters of properties, but you can mix private/public access of getter/setter methods, in similar style as Java:
private prop:int;
public getProp():int { return prop; }
private setProp(value:int):void {
prop = value;
}
This is not as common of a style you see in AS3 because we have formal get
/set
property syntax, but it's still perfectly valid.