Thursday, June 21, 2007

Using public namespace explicitly

Having same function in two or more name spaces can cause the following compiler error when trying to access the function. 1000: Ambiguous reference to foo. This error is easily generated when "using namespace " has been included in the file instead of referring to the namespace explicitly.
myspace.as

package
{
  public namespace myspace = "http://myspace";
}

TestClass.as

package
{
import myspace;

public class TestClass
{

  public function foo():void
  {
 trace("Public foo is called");
  }

  myspace function foo():void
  {
 trace("MySpace foo is called");
  }

  private function fooPrivate():void
  {
 trace("Called private function");
  }

  protected function fooProtected():void
  {
 trace("Called protected function");
  }

  public function callFoo(t:TestClass):void
  {
        // call the private/protected members on the object.
 t.fooPrivate();
 t.fooProtected();
  }
}
}

testApp.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
 creationComplete="testFunc()">
<mx:Script>
 <![CDATA[

use namespace myspace;

private function testFunc():void
{
   var test:TestClass = new TestClass;
   //public can be also used as namespace name to call the correct function.
   test.public::foo();

   // call the myspace namespace function
   test.myspace::foo();

   var test2:TestClass = new TestClass;
   // call the function to demonstrate that private/protected functions
   // can be called on test2 object.
   test.callFoo(test2);

}
]]>
</mx:Script>
</mx:Application>
The above example also shows the possibility of calling private/protected functions on an object of the same class within the functions of the class. I don't think this is allowed in languages like C++. Note: As Richard has commented it is alllowed in C++ too. I think it makes sense as friend functions can access private variables of objects member functions should be able to access them too.

2 comments:

Anonymous said...

It is allowed in C++.

Sreenivas said...

Thanks. Richard. I think after working on AS for 2 years I have started forgetting my C++ fundamentals :-)