![]() |
Tutorial01 | HelloWorld - The traditional start of a programming adventure |
Max-compatible Java classes are prototypes that define the variables and methods common to all objects of their kind. Your task in programming for the mxj object will be to extend a class called, MaxObject, which contains methods that interface with the Max world. When you create a new Max object by typing mxj MyClass in an empty object box, mxj instantiates (creates an instance of) two objects a Java object of the MyClass class, and a peer mxj object to "contain" the Java object.
The first example we'll look at is a classic. Upon instantiation of the object, "hello world!" is printed in the Max console. Here is the code for the HelloWorld1 Java class:
import com.cycling74.max.*;
public class HelloWorld1 extends MaxObject {
public HelloWorld1() {
post("hello world!");
}
}
Short and sweet. Let's examine the blocks of the code in detail, starting with the import statement at the top. This first line is what allows our class to use all of the essential classes and methods of the mxj API. It's also possible to import any of the classes from the 1.4 Java API, or from a third-party library, but for this class everything we need is in the max.jar package that Cycling '74 provides.
The next block defines our class as a subclass of the primary occupant of the imported API, MaxObject:
public class HelloWorld1 extends MaxObject {
...
}
The public modifier in front of the class declaration simply means that the class can be accessed by outside programs. To exist in the Max universe, a Java class must be a subclass of MaxObject - this relationship is declared with the extends keyword. A subclass inherits all the public variables and methods of its superclass. MaxObject contains many methods which allow your Java code to interact with Max, but for this first example we only use its post method, which outputs a String argument to the Max console.
public HelloWorld1() {
post("hello world!");
}
The above code is the HelloWorld1 class's constructor, a method that is called every time a new object of the class is instantiated. In the context of Max programming this method is called when a new mxj object with an argument of HelloWorld1 is created. The constructor must have the same name as the class it is constructing.
The HelloWorld1 class's constructor method is pretty silly: we call post and ask it to output "hello world!" to the Max Window. As you can see from the picture below, mxj obliges. At this point it might be worthwhile to open up HelloWorld1.java, replace "hello world!" with something more exciting, and then confirm that you're able to compile and instantiate your new and improved HelloWorld1 class.
Example: |