有三个与此主题相关的术语:声明,初始化和实例化.
从后到前工作.
实例化
这是为对象分配内存的时候.这就是新关键字正在做的事情.从new关键字返回对创建的对象的引用.
初始化
这是将值放入已分配的内存中的时间.这是使用new关键字时类的Constructor.
还必须通过将对内存中某个对象的引用传递给它来初始化变量.
宣言
这是当您向程序声明将存在某种类型的对象以及该对象的名称时.
同一行上的初始化和实例化示例
SomeClass s; // Declaration
s = new SomeClass(); // Instantiates and initializes the memory and initializes the variable 's'
在与内存不同的行上初始化变量的示例
void someFunction(SomeClass other) {
SomeClass s; // Declaration
s = other; // Initializes the variable 's' but memory for variable other was set somewhere else
}
我还强烈建议阅读this article关于Java如何处理传递变量的性质.