Access Modifiers in ActionScript 3.0
The Basic Access Modifiers are
- internal
- private
- public
- protected
internal is the default access modifier which is used if no other modifier is specified. It allows internal access and package-level access. Unlike in ActionScript 2.0 where it was treated as public, internal is not public but internal by default in ActionScript 3.0.
private is strictly private in ActionScript 3.0. Private is the most restrictive access modifier. It only allows internal access to members and it does not allow package-level access nor access from subclasses.
public is the least restrictive access modifier and thus allows access from anywhere.
protected allows internal access to members and access from subclasses but restricts package-level access.
Let us look at some sample codes
package
{
import flash.util.trace;
import flash.display.Sprite;
public class A extends Sprite
{
public function A()
{
var accessB:B = new B();
accessB.internalMethod();
// Error: Method is protected cannot be accessed
accessB.ProtectedMethod();
// Error: Method is private cannot be accessed
accessB.PrivateMethod();
// class C inherits from class B
var accessC:C = new C();
// B ProtectedMethod can be accessed via Derived class method
// it cannot be accessed by instance
// Error: cannot Access via instance method
accessC.ProtectedMethod()
// can be accessed only b class C
accessC.accessProtectedMethod();
}
}
private class B
{
public function B()
{
//ProtectedMethod();
}
protected function ProtectedMethod()
{
trace("Protected can be accessed by me and my children(subclass");
}
internal function internalMethod()
{
trace("i am internal can be accessed in Package Level");
}
private function PrivateMethod(){
trace("i am Private cannot be accessed anywhere except me");
}
}
private class C extends B
{
public function C()
{
// I can acess my parent ProtectedMethod
//super.ProtectedMethod();
}
public function accessProtectedMethod()
{
super.ProtectedMethod();
}
}
}
Private and Protect
Often Private and Protect can create some level of confusion to a Programmer evenso their difference is very subtle. In short, Protected means it is “Private to all other Classes, except for Subclass”. So, Subclasses alone can access the protected method. But when it is private even subclass cannot access it.
Can Subclass inherit private access modifiers from Super Class?
No, Subclasses cannot inherit and access the private acess modidiers.
Comments
Post a comment