![]() |
Tutorial06 | autocount1 - Attributes |
In this example we introduce the attribute system, a particularly painless way of interfacing your class's variables with the world of Max.
import com.cycling74.max.*;
public class autocount1 extends MaxObject {
private int count=0;
public autocount1() {
declareAttribute("count");
}
public void bang() {
count++;
outlet(0, count);
}
}
The count variable is an integer and has been declared like any other integer might be declared. In the class's constructor, however, the declareAttribute method has been passed the name of the variable as a String. This will register count as an attribute, which automatically gives it some very nice functionality.
The primary functionality afforded to an attribute is the automatic, background support for setting and getting the value of the variable in a Max patch. If the Max user sends a "count 8" message to an autocount1 object the value of the count will be set to 8. If the user were to then send a "get count" message into the object, an 8 would be sent out the object's right outlet.
In some situations you may want to provide your own set or get method for an attribute - for instance, if you want to limit input values to a particular range, or if you want your get method to provide additional information beyond just the value of the variable. To do this it's necessary to call declareAttributes(String, String, String), where the second and third Strings should be the names of the getter and setter methods, respectively. Passing null for either of these enables the default automatic get or set implementation. To be a valid setter a method must have a return type of void; to be a valid getter a method must have a return type of Atom[].
The other major bit of functionality that attributes enjoy is the ability of the user to access an attribute's set method from instantiation arguments. If that instantiation arguments for a new autocount1 object include "@count", the subsequent value will be passed to count's set method sometime after the constructor method has finished executing. Please note that since a setter method can be called at construction time, similarly to the constructor a setter should not send data out the object's outlets.
The class itself is pretty basic - like the counter object, autocount1 sends out an increasing integer with each bang. Things will get more interesting in autocount2.
Example: |