
"Hi, it's your favorite teacher again. Since you're making such great progress, I've decided to tell you about objects and how to work with them."
"To create an object, you need to type the keyword 'new' followed by its type name (class name). For example, suppose we have a class named 'Cat':"
Code | Description |
---|---|
|
Declares a Cat reference variable named cat. The variable cat's value is null. |
|
Creates a Cat object. |
|
Creates a Cat reference variable named cat. Creates a new Cat object. Assigns a reference to the newly created object to the variable cat. |
|
Two objects are created. References to them are assigned to two different variables. |
|
Two objects are created. References to them are assigned to two different variables.
Then we set the variable smokey equal to a reference to the object referenced by the variable kitty. Both variables now refer to the first created objects. |
|
One Cat object is created, and a reference to it is assigned to the first variable (kitty). The second variable (smokey) stores an empty (null) reference.
Both variables refer to the same object. Now only smokey, but not kitty, refers to an object. |
"What would happen if we created an object and didn't save a reference in any variable?"
"If we just create an object without assigning it to a variable, the Java machine will create it and then declare it garbage (an unused object). After a while, the object will be disposed of during garbage collection."
"How do I dispose of an object I don't need anymore?"
"You don't. As soon as no variables refer to an object, it is labeled as garbage and destroyed by the Java machine the next time it collects garbage."
As long as there is at least one reference to an object, it's considered active and will not be destroyed. If you want to dispose of an object sooner, you can clear all references to it by assigning null to all variables that reference it.
"I see. Compared to the last few lessons, this looks pretty simple."
"Diego has been up all night thinking up tasks for you. He made this special effort just for you. He has a great sense of humor, you know?"
A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.
GO TO FULL VERSION