There are three pieces of terminology associated with this topic: declaration, initialization and instantiation.
Working from the back to front.
Instantiation
This is when memory is allocated for an object. This is what the new
keyword is doing. A reference to the object that was created is returned from the new
keyword.
Initialization
This is when values are put into the memory that was allocated. This is what the Constructor of a class does when using the new
keyword.
A variable must also be initialized by having the reference to some object in memory passed to it.
Declaration
This is when you state to the program that there will be an object of a certain type existing and what the name of that object will be.
Example of Initialization and Instantiation on the same line
SomeClass s; // Declaration
s = new SomeClass(); // Instantiates and initializes the memory and initializes the variable 's'
Example of Initialization of a variable on a different line to memory
void someFunction(SomeClass other) {
SomeClass s; // Declaration
s = other; // Initializes the variable 's' but memory for variable other was set somewhere else
}
I would also highly recommend reading this article on the nature of how Java handles passing variables.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…