Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initializing a class and instantiating an object?

Tags:

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?

like image 233
arnold_palmer Avatar asked Feb 25 '13 18:02

arnold_palmer


People also ask

What does initializing a class mean?

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.

What is the difference between declaring and instantiating in Java?

Declaring - Declaring a variable means to introduce a new variable to the program. You define its type and its name. Instantiate - Instantiating a class means to create a new instance of the class.

What is the difference between initializing and declaring?

Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.

What does it mean to instantiate an object?

To instantiate is to create such an instance by, for example, defining one particular variation of an object within a class, giving it a name and locating it in some physical place.


1 Answers

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.

like image 124
lachy Avatar answered Sep 24 '22 23:09

lachy