All objects in Java are defined based on a basic object, java.lang.Object. This Object object will allow Java to handle all objects from the time they are created until they are no longer used. In this tutorial, we will learn more about what I just said.
Unlike other programming languages, Java manages objects by allocating memory as they are created and maintains memory if those objects are no longer usable.
Maintenance of memory, if objects are no longer used, will be handled by Java’s garbage collector. This process will run periodically and it will free up the memory of objects that are no longer used.
When will the object be no longer used? The answer is when the object is no longer referenced to any variable.
To understand more, now we will learn together about the life cycle of an object.
Initialize an object
The object is created using the new operator and we can assign this object reference to any variable. There is a difference between declaring and initializing that object when declaring that we do not use the new operator while initializing.
The following example will help you see this, we have Student object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.huongdanjava; public class Student { private String name = "Khanh"; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
To declare the Student object in the Example class we do the following:
1 2 3 4 5 6 |
package com.huongdanjava; public class Example { private Student student; } |
To initialize it, the code would look like this:
1 2 3 4 5 6 |
package com.huongdanjava; public class Example { private Student student = new Student(); } |
The object after initialization, we can access its properties using the variable reference to it.
When objects are no longer accessible?
In the case, after initializing the object and assigning it a reference variable, we reassign this reference variable to another object, which will then be inaccessible.
The following example will help you to better understand:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava; public class Example { public static void main(String[] args) { Student student = new Student(); student.setName("A"); student = new Student(); student.setName("B"); } } |
In the above example, the student variable after assigning the Student object named A, is assigned to the Student object named B, and so they can no longer access the Student object named A.
An object that is not referenced to any variable cannot be accessed from anywhere. This object is then collected by the Java garbage collector.