Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

java - Difference between initializing a class and instantiating an object?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...