Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


Share this Page URL
Help

Classes > Constructor - Pg. 24

24 Your First inFormation-rich application methods Methods are added in a way similar to properties, except that the keyword is function. To be very concise a method is an old- style function (like in ActionScript 2) with a specifier. Let's add a greetingmethodtoourPersonclass. package com.studiomagnolia.model { public var name:String; public class Person() {} public function greet():String { return "Hello" + name; } } Have a method that does not return any value? Just declare its return type as void. Here we have defined a public method greet, which returns a string made by "Hello" plus the name of the person. Like prop- erties, methods have four visibility specifiers: · Private--can be called just by the class itself · Protected--only class and subclasses can call it · Internal--only classes from the same package can call it · Public--everybody can call it As with properties, the default value is internal. constructor As we said above the constructor is a special method called when an instance of a class is created. By rule, the constructor has to be public and there is no need to specify a return type. At instantiation time we are allowed to pass parameters, which populate the instance. For example, let's say that by design a per- son with no name can't exist. One way to implement this require- ment is to pass the name as a parameter in the constructor. So we refactor our class like in the following code. package com.studiomagnolia.model { private var name:String; public class Person(name:String) { this.name = name; } // greet method omitted. } This definition changes the way we can use the class. We can- not create an empty instance of person anymore--we have to specify a name at instantiation time, as in this code. var p:Person = new Person("Cesare"); What if the designer changes her mind and says: "Name is optional, it might or might not be specified"? We can exploit