Actionscript 3: Inheritance Subclass and private vars

I’m currently updating some as2 projects to as3 and I had a series of 1120 compiler errors this afternoon. I’m a fan of using the ‘extends’ keyword to create customised versions of base classes.

In Actionscript 2 the subclass can access all the variables and methods of the original class. It appears that in ActionScript 3, things are much stricter and only public variables and methods are accessible.

For example, this won’t work:

A.as

package
{
public class A{
private var propertyA:String = "Private Property from the A class";

public function A(){
trace("A.A()");
}

public function methodA(){
trace("---A.methodA()----");
trace("- propA:"+propertyA);
}
}
}

B.as

package
{
import A;

public class B extends A{
private var propertyB:String = "Private property from the B class";

public function B(){
trace("B.B()");
}

public function methodB(){
trace("---B.methodB()----");
trace("- propA:"+propertyA);
trace("- propB:"+propertyB);
}
}
}

The compiler error is:
1120: Access of undefined property propertyA.

But if you change the private var propertyA (in A.as) to public var propertyA, then the compiler is error free.

This entry was posted in Code, flash and tagged , , , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Sprague
    Posted June 29, 2010 at 1:39 am | Permalink

    Thanks – This was a total help!

  2. Posted August 25, 2010 at 11:03 pm | Permalink

    your situation (and mine as ov 5 minutes ago) can be solved by swapping “private” for “internal”. I’ve had errors with private functions, which won’t compile when I’m trying to do simple overrides, and say for example inheriting a variable. A bunch of examples I had a while back from a cookbook kept using internal. I’m no oop guru, I’m still trying to get to grips with the whole thing, so i don’t know why private fails and internal works or what their difference is

  3. Posted August 26, 2010 at 10:34 am | Permalink

    Hi Paul, Yep you’re right. I did a quick bit of research. As I understand it now the keyword internal is like private but for the entire package, not just the individual class. So that would make it usable in the above example as extended classes are in the same package.

    Thanks

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>