new and a matching constructor call.class Student { String name; Student() { name = "New Student"; } }, calling new Student() runs Student() and assigns New Student to name.Student() { }.Student(int id, String name) { ... }.β Must-know
π A constructor's name must be identical to its class name, and a constructor has no return type.
Further detail
staticfinalabstractsynchronizedβ Must-know
Constructor overloading means creating constructors with different parameter lists.
Constructor chaining uses this() to chain constructors within a class and super() to chain across inheritance; either call must appear before any other statement in the constructor.
Further detail
π A constructor call must match the number and types of arguments accepted by the constructor.
β Must-know
π A class describes structure, while each object created from the class has its own state.
new and a constructor, object use through a reference, possible eligibility for garbage collection when no live path reaches itπ Method-call frames and local variables or references are commonly associated with the stack, whereas objects are generally allocated in the heap.
Further detail
Student s = new Student();, the variable s refers to the Student object created by new Student().π Assigning
nullto a reference means that reference no longer points to the object, but another reference may still reach it.
β Must-know
π An object is reachable when a live reference path leads to it; an object is unreachable when no live reference path reaches it and may then be eligible for garbage collection.
π Java manages object memory automatically, but files, sockets, and database connections still need to be closed properly.
Further detail
Calling System.gc() does not force the JVM to collect a specific object immediately.
Calling a method through a null reference is a common programming error.
Reachable, unreachable, eligible, then possibly collectedβnot necessarily immediately.
Take a 12-question practice quiz on Java Constructors and Object Lifetime, with every answer explained.
1. When does a constructor prepare an object by initializing fields or performing setup?
2. Given `class Student { String name; Student() { name = "New Student"; } }`, what is the result of evaluating `new Student()`?
Memorize the key concepts of Java Constructors and Object Lifetime with 30 flashcards.
What does a constructor do when preparing a new object?
It initializes fields or performs setup.
When does a constructor run during object creation?
When the program creates an object with `new` and a matching constructor call.
What must a constructorβs name match?
Its class name.
Upload your class notes and Revizly writes a study guide, a quiz and flashcards in about a minute.
Study guide maker