All properties and methods are public by default. You don't have to declare them public with the public keyword but you can if you want to spell it out. Private properties and methods, however, have to be declared as such. If you create an instance of the Hello class and then use that instance to call the sayHello() method, you will get an error. If the sayHello() method was public, you wouldn't get the error. The only class that can access the private sayHello() method is the Hello class itself. Below is an example. The sayHello() method cannot be accessed from outside of this class, including from class instances. But since the public sayHelloAnyway() method calls the private sayHello() method, sayHello() is indirectly available to class instances. The above code results in a "hello" trace in the output window. It does not cause an error.
When a method is public, it means that it is accessible by the original class and by all instances of that class. When a method is private, it is only accessible by the original class. Below is a class with a private sayHello() method.
class Hello {
private sayHello() {
trace("hello");
}
}
var greeting:Hello = new Hello();
greeting.sayHello(); // will create an error saying "The member is private and cannot be accessed."
// Hello.as:
class Hello {
// a private method
private function sayHello() {
trace("hello");
}
// a public method which accesses the private method
function sayHelloAnyway() {
sayHello();
}
}
//separate.fla
var greeting:Hello = new Hello();
gretting.sayHelloAnyway();
Private methods are useful for internal processes that you don't need to or don't want to be exposed to the public. I am sure you can think of much better examples than the one above.
|





posted
by Vera Fleischer (