java 初始化和实例化,初始化类和实例化对象之间的区别?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值