Methods in ActionScript
ActionScript supports methods defined on class types. Here’s an example:
package {
import flash.display.Sprite;
import flash.text.TextField;
public class Methods extends Sprite {
public function Methods() {
var r:Rectangle = new Rectangle(10, 5);
var tf:TextField = new TextField();
tf.text = "area: " + r.area() + "\n";
tf.text += "perim: " + r.perim() + "\n";
// ActionScript doesn't have pointers, so we'll use the same instance
tf.text += "area: " + r.area() + "\n";
tf.text += "perim: " + r.perim();
addChild(tf);
}
}
}
class Rectangle {
private var width:int;
private var height:int;
public function Rectangle(w:int, h:int) {
width = w;
height = h;
}
// This `area` method is defined on the Rectangle class
public function area():int {
return width * height;
}
// Methods in ActionScript are always defined on the class itself
public function perim():int {
return 2 * width + 2 * height;
}
}
In this ActionScript example, we define a Rectangle
class with width
and height
properties, and two methods: area()
and perim()
.
The area()
method calculates and returns the area of the rectangle.
The perim()
method calculates and returns the perimeter of the rectangle.
In the Methods
class (which extends Sprite
to allow it to be used as the main class in a Flash application), we create an instance of Rectangle
and call its methods.
ActionScript doesn’t have the concept of pointer and value receivers like Go does. All methods in ActionScript are defined on the class itself, and instances of the class can call these methods directly.
We use a TextField
to display the results, as ActionScript is typically used in a graphical context.
To run this code, you would need to compile it with the ActionScript compiler and run it in a Flash player or AIR runtime environment.
Next, we’ll look at ActionScript’s mechanism for defining interfaces, which allow for polymorphism and abstraction in object-oriented programming.