With the capability for starting and stopping a program, plus variable definition and assignment, we can now use the previously developed data type Dog. First, we modify SimpleProgram to have a more meaningful name, for example, ADogsLife:
public class ADogsLife {
public static void main(String[] args) {
System.exit(0);
}
}
Next, we define the program's behavior in terms of its main() method. Specifically, main() creates an instance of Dog named dog (case is significant in Java(TM)) and provokes the dog to bark:
public class ADogsLife {
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark();
System.exit(0);
}
}
In Java, as with other languages, a program allocates objects dynamically. Java's storage allocation operator is new:
Storage Allocation Syntax |
new <data-type>(<arguments>...) |
<data-type> <variable> = new <data-type>(<arguments>...) |
The new operator asks the Java runtime environment to create dynamically (on the fly) an instance of a user-defined data type, for example, "new Dog()". You can also associate the instance with a variable for future reference (hence, the term reference variable), for example, "Dog bowwow = new Dog()". The data type for the reference variable bowwow must be specified to the left of the variable name, in this case, "Dog bowwow".
Objects receive their storage on/from the heap, which is simply a memory pool area managed by the Java interpreter. The following diagram illustrates the memory allocation for the class files, plus the instance of Dog allocated on the heap:
Exercise
copyright 1996-2000 Magelang Institute dba jGuru