Lesson 5
public - private - internal
We will now discuss in more detail the attributes public, private and internal, which are used for variables and functions. First of all, all functions have to have the one of those attributes, otherwise there will be a warning. Then by default all variables and functions are internal, if we do not write the specific attribute. This is different from AS2 where all functions and variables were public by default and we do not have to add the attribute. "internal" did not exist and as you will see is specific for the package structure. Now let's look at an example.
Unlike in AS2 where you were able to call and display the contents of a private variable using this syntax, in AS3 it is not possible any more. If you check Starter_5.swf in your browser, there is nothing and that is good.
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class Starter_5 extends Sprite
{
private var tField:TextField;
public function Starter_5 ()
{
myTest();
}
private function myTest():void
{
var a:Testvar = new Testvar();
tField = new TextField();
tField.text = String(a["test"]);
addChild(tField);
}
}
}
//
import flash.display.Sprite;
class Testvar extends Sprite
{
private var test:String;
public function Testvar()
{
test = "I am a string";
}
}
So now change private var test:String; to public var test:String; and create a new movie. Now the variable content will be shown. A different scenario is when a private var is called in a getter method, which we will see later. Since the getter is a public function the variable content will be shown.
AS3 has an additional attribute internal, which we will discuss next.