I tried searching for this question through the search engine but could find a topic that explained the difference between initializing a class and instantiating an object.
Could someone explain how they differ?
解决方案
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.
本文详细解释了类的声明、初始化和实例化的概念。实例化是指为对象分配内存,new关键字用于此操作。初始化则是将值放入已分配的内存中,通常由类的构造函数完成。变量声明则指明将存在一个特定类型的对象。文章还提供了一个示例来说明这两者的区别,并推荐了一篇关于Java变量处理的文章进行深入阅读。
580

被折叠的 条评论
为什么被折叠?



