PDA

View Full Version : I thought protected vars were inherited by subclasses!


Mazoonist
04-06-2008, 02:02 PM
Okay, I haven't used inheritance that much, I admit. So I'm studying the subject in Essential Actionscript 3.0, and wanting to apply it to my projects.

I hit kind of a snag. I thought protected vars (and methods) would be inherited by subclasses as long as they're in the same package. So, I don't understand why the following won't work for me (just a really simple example):

One.as:
package {
public class One {
protected var foo:String;
public function One() {
foo = "bar";
}
}
}
Two.as:
package {
public class Two extends One {
public function Two() {
super();
}
}
}
Then in a fla file saved to the same folder, I create a new instance of Two, which should inherit the foo variable from One:
var two:Two = new Two();
trace(two.foo);
This causes an error (!) :
1178: Attempted access of inaccessible property foo through a reference with static type Two.
but works fine if I change the access control modifier on foo to "public" instead of "protected." But I should be able to use protected, so what am I doing wrong?

It's gotta be something simple. What am I missing (besides a brain)?

Mazoonist
04-06-2008, 02:26 PM
I believe I know the answer. I think that only code inside the subclass would be allowed to access the protected variable, and not any other external code.

wvxvw
04-06-2008, 04:32 PM
Yes, you're right, protected vars in AS3 (unlike Java) are accessible only to classes extending the class that has those variables declarations. If you want to protect varables so thay will be visible only to classes in a project - use custom namespaces. I.e. declare namespace on the project level and then use it with var's declaration:
package player {

public namespace player_internal = 'PI';
}
than:
package player {

import player.player_internal;
....
public class Player extends EventDispatcher {

use namespace player_internal;

player_internal var timer:Timer;
....