What is the difference between initializing a class and instantiating an object




















T he terms instantiate, declare, and initialize are easy to stumble upon while programming. But what exactly do these terms mean? In a statically typed language like Java, this also means that the declared type of the variable is determined. The value itself is not determined during the declaration. 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. 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.

I would also highly recommend reading this article on the nature of how Java handles passing variables. Initializing a class is done using a static initialization block.

It's not a method, it's an initializer. It is executed the first time the class itself is referenced. Instantiating an object is done for example with new keyword by calling its constructor. At that time static initialization block will not be executed. If you add any files,it will delete all existing files related to this question- questions only answer remains unchanged.

Your request will be Queued. We will review the question and remove. The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:. This statement will be discussed in the next section. This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code int a, int b.

The following statement provides 23 and 94 as values for those arguments:. Each constructor lets you provide initial values for the rectangle's origin, width, and height, using both primitive and reference types. If a class has multiple constructors, they must have different signatures. The Java compiler differentiates the constructors based on the number and the type of the arguments. Ask a Question.

Could someone explain how they differ? Please log in or register to add a comment. Please log in or register to answer this question. Working from the back to front. Instantiation This is when memory is allocated for an object. Initialization This is when values are put into the memory that was allocated. 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.

Related questions. Technically what are the meanings and differences of the terms declaring, instantiating, initializing and assigning an object in C?



0コメント

  • 1000 / 1000