Monday 15 October 2012

AS3 – internal class, public method


package testPackage {
   public class PublicClass {
 
      public function returnInternalClassRef():InternalClass {
         return new InternalClass();
      }
   }
}

package testPackage {
   internal class InternalClass {
 
      public function doSomething():void {
         trace("InternalClass did something!!");
      }
 
      internal function doSomethingInternally():void {
         trace("InternalClass did something internally!!");
      }
   }
}

package {
 
   import flash.display.Sprite;
   import testPackage.PublicClass;
 
   public class InternalTest extends Sprite {
      public function InternalTest() {
 
         var publicClass:PublicClass = new PublicClass();
         var ref:Object = publicClass.returnInternalClassRef();
         ref.doSomething();
         ref.doSomethingInternally();
      }
   }
}



Now make a guess, what happens?
Well, it’s not too hard to figure out, right? But interesting to remember anyway. The call for doSomething() works, whereas the call for doSomethingInternally() ends up in an exception. So if you define an internal class, you can still pass its reference outside its package (loosing the type obviously). Any public methods can be called then, but internal methods not. Makes sense, does it? I was just thinking about it, because i asked myself, why one would declare a class internal, but still have public methods.
So it only makes sense, if you want to pass it around as either an untyped reference or as a casted interface implementation. Means, you could have an interface outside the package and the internal class implements it. Then within the package you could use the class by its direct class type and outside you would use it by its interface type.

No comments:

Post a Comment