Namespace in ActionScript 3.0
In general Namespaces allow for group entities like classes, objects and functions under a name. In ActionScript 3.0, Namespaces works like namespaces in an XML. It allows for the control of the visibility of class members.
How to declare Namespace?
namespace ;
@ function @
Example
namespace AddString;
namespace AddNumber;
//
AddString function Sum(a:String,b:String):String
{
return a+b;
}
//
AddNumber function Sum(a:Number,b:Number):Number
{
return a+b;
}
How to use Namespace?
Now you can access the Namespace funtions in 2 ways.
- Using ‘use’ keyword
- Using fully qualified name (:: notation)
from the previous example we declared now we can use in 2 ways
// 1.
use AddString
Sum("santosh","kumar");
//
use AddNumber
Sum(1,2);
// 2.
AddString::Sum("santosh","kumar");
AddNumber::Sum(1,2);
Using NameSpace, we can have same function name defined any number of times. for example function Sum is defined twice for addition of string and as well as for addition of number.
Let us look at the following codes
package
{
import flash.util.trace;
import flash.display.Sprite;
//
public class Addition extends Sprite
{
namespace AddString;
namespace AddNumber;
//
public function Addition()
{
trace ( AddString::Sum("Hello","World"));
trace ( AddNumber::Sum(1,2));
}
//
AddString function Sum(a:String,b:String):String
{
return a+b;
}
//
AddNumber function Sum(a:Number,b:Number):Number
{
return a+b;
}
}
}
Note
1. If we declare namespace in package we can use same namespace name in multiple classes.
for e.g.
package
{
namespace X
public class A
{
public function class A()
{
X::someMethod()
}
X function someMethod()
{
}
}
//
public class B
{
public function class B()
{
X::someMethod()
}
X function someMethod(){
}
}
}
Here, the same Namespace X is used in class A and class B
2. When using Namespaces you cannot specify access modifier like private, public etc
for e.g.
namespace X
// Errror: Access specifiers not allowed in namespace attributes
X private function someMethod()
{
}
3. Namespaces cannot be used like C++ for declaring properties or variables
// Error:
namespace myNamespace
{
int a, b;
}
4. The namespace of superclass can be accessed via subclass using keyword ’super’
super.::
Comments
Nice to know, but more interesting is why should you use the namespace. It looks like an elaborate way to have overload / polymorphism capabilities and global util functions
thanks and your explanation was good enough for understanding namespace’s usage. I have one doubt regarding URI which is called namespace name . Can you explain it in a better way with example. It will be very helpful.
regards,
vidya.
Great post. I love the idea of assisting developers so they only seeing the methods via intellisense (of Flex Builder) for methods they need to see. I created a new demo to show that off. http://www.blog.rivello.org/?p=422
var a =5; namespace.