- Java 9:Building Robust Modular Applications
- Dr. Edward Lavieri Peter Verhas Jason Lee
- 169字
- 2025-04-04 17:08:34
Object creation
Objects are declared and created. When we write an object declaration, or declare an object, we are declaring a name or identifier so that we can refer to an object. For example, the following line of code declares myObjectName as the name of an object of type CapuchinMonkey. At this point, no object was created and no memory allocated for it:
CapuchinMonkey myObjectName;
We use the new keyword to create an object. The following example illustrates how to invoke the new operation to create an object. This operation results in:
myObjectName = new CapuchinMonkey();
Of course, we can combine the declaration and creation statements together by using CapuchinMonkey myObjectName = new CapuchinMonkey(); instead of CapuchinMonkey myObjectName; and myObjectName = new CapuchinMonkey();. They were separated in the preceding example for illustrative purposes.
When an object is created, a specific amount of memory is allocated for storing that object. The amount of memory allocated can differ based on architecture and JVM.
Next look at the mid-life of an object.