![]() ![]() ![]() | |
![]() | |
![]() | |
![]() |
By default, any property or method of a class can be accessed by any other class: all members of a class are public by default. However, in some cases you may want to protect data or methods of a class from access by other classes. You'll need to make those members privateavailable only to the class that declares or defines them.
You specify public or private members using the public
or private
member attribute. For example, the following code declares a private variable (a property) and a private method (a function).
For example, the following class (LoginClass) defines a private property named userName
and a private method named getUserName()
.
class LoginClass { private var userName:String; private function getUserName() { return userName; } // Constructor: function LoginClass(user:String) { this.userName = user; } }
Private members (properties and methods) are accessible only to the class that defines those members and to subclasses of that original class. Instances of the original class, or instances of subclasses of that class, cannot access privately declared properties and methods; that is, private members are accessible only within class definitions; not at the instance level.
For example, you could create a subclass of LoginClass called NewLoginClass. This subclass can access the private property (userName
) and method (getUserName()
) defined by LoginClass.
class NewLoginClass extends LoginClass { // can access userName and getUserName() }
However, an instance of LoginClass or NewLoginClass cannot access those private members. For example, the following code, added to a frame script in a FLA file, would result in a compiler error indicating that getUserName()
is private and can't be accessed.
var loginObject:LoginClass = new LoginClass("Maxwell"); var user = loginObject.getUserName();
Also note that member access control is a compile-time only feature; at runtime, Flash Player does not distinguish between private or public members.
![]() | |
![]() | |
![]() | |
![]() ![]() ![]() |