program story

"인스턴스화"와 "초기화"의 차이점은 무엇입니까?

inputbox 2020. 8. 25. 07:57
반응형

"인스턴스화"와 "초기화"의 차이점은 무엇입니까?


VB.NET에 대한 Microsoft 자습서에서 사용되는이 두 단어를 들었습니다. 변수와 관련하여 사용될 때이 두 단어의 차이점은 무엇입니까?


가치 기준 참조 유형

C #의 변수 는 두 그룹 중 하나에 있습니다. 유형 또는 참조 유형. int같은 유형 DateTime 유형입니다. 반대로 생성하는 모든 클래스는 참조 유형입니다. C # 문자열도 참조 유형입니다. .NET 프레임 워크의 대부분은 참조 유형입니다.

변수의 일부

변수 이름이 있고 value 입니다. 두 부분 .

변수의 이름 은 사용자가 선언 한 것입니다. 값은 당신이 무엇을 할당하는 그것.

변수가 초기화 됨

모든 변수는 변수가 선언 되는 시점에서 항상 초기 값이 주어집니다 . 따라서 모든 변수가 초기화 됩니다.

들어 유형처럼 int그렇게 명시 적으로하지 않으면 컴파일러 그들에게 올바른 가치를 제공 할 것입니다. int의는 초기화 기본적으로 제로로, DateTime의는 초기화DateTime.MinValue기본적으로.

참조 유형 변수 는 사용자가 제공 한 객체로 초기화 됩니다. 그렇지 않으면 컴파일러는 객체 (즉, 유효한 값)를 할당 하지 않습니다. 이 경우 값은 null-없음입니다. 그래서 우리는 참조가 null 초기화 되었다고 말합니다 .

개체가 인스턴스화됩니다.

인간이 태어났습니다. 개체가 인스턴스화됩니다. 아기는이다 예를 인간의 객체는이다 예를 몇 가지 클래스의.

클래스 인스턴스 를 만드는 행위를 인스턴스화 (Ta-Da!)라고합니다.

따라서 다음 과 같이 선언 , 초기화인스턴스화 가 함께 제공됩니다.

MyClass myClassyReference = new MyClass();

위에서 "... 객체 의 인스턴스를 만드는 중 ..."이라고 말하는 것은 잘못된 것입니다 .


편집-댓글 토론에서 영감을 얻음

별개의 용어를 사용하여 위의 세 가지 별개의 작업이 진행되고 있으며 해당 용어는 서로 바꿔서 사용할 수 없습니다.

  1. 참조 변수가 선언되었습니다. MyClass myClassyReference
  2. 객체가 인스턴스화됩니다 (... 주어진 클래스 에서 / 내포 됨)-new MyClass()
  3. 개체가 변수에 할당됩니다. =.

사실을 다시 말함 :

  1. 참조 유형 변수는 단순히 "참조"라고도합니다. "값 유형 변수"는 참조가 아닙니다.

  2. 이것은 "objectA는 객체의 인스턴스입니다"는 완전히 잘못되었습니다. objectA가 "objectB의 인스턴스"였다면 objectA는 objectB의 유형 (어떤 것이 든 현재 상태)으로 생명을 시작해야합니다. objectB가 변경되면 개체 D, E 및 F를 만드는 것은 어떻습니까? 아니, 아니! "objectA는 클래스의 인스턴스"라는 개념적이고 기술적 인 경우입니다. "Instantiation"및 "instance of"는 정확한 의미를 갖습니다. 객체는 클래스에서 유형, 정의 및 값을 가져옵니다.

  3. MyClass myClassyReference = null일반적으로 우리는 "변수가 null에 할당 됨"이라고 말하지 않고 "변수가 null을 참조합니다"라고 말하지 않습니다. 대신 "변수가 null입니다"라고 말합니다. 또는 "변수가 아무것도 참조하지 않습니다."또는 "참조가 null입니다."

실용적인 응용 프로그램:

  • 나는 당신의 코드에 손가락을 대고 "이 인스턴스에는 유효하지 않은 속성이 있습니다. 이것이 루프가 실패하는 이유입니다. 인스턴스화하는 동안 매개 변수를 검증해야합니다."라고 말합니다. (즉, 생성자 인수).

  • 나는 당신의 코드에서 이것을 본다.

    MyClass myClassyReference;
    myClassyReference.DoSomething();
    

    "변수를 선언했지만 할당하지 않았습니다. null이므로 아무 것도 참조하지 않습니다. 이것이 메서드 호출에서 예외가 발생하는 이유입니다."

편집 종료


참을 수없는 존재의 가벼움

기준 입력 변수의 이름과 값은 독립적으로 존재한다. 그리고 나는 독립을 의미합니다.

인스턴스 객체에 대한 참조도있을 수도 있고 없을 수도 있습니다.

인스턴스 객체는 많은 참조가있을 수 있습니다.

A는 선언 참조 수도 있고되지 않을 수도 를 가리키는 객체.


변수는 값으로 초기화된다. 객체는 메모리가 그것을 위해 할당되고 그것의 생성자가 실행되었을 때 인스턴스화됩니다.

예를 들어 다음은 변수입니다.

Dim obj as Object

이 변수는 초기화 되지 않았습니다 . obj변수에 값을 할당 하면 변수가 초기화됩니다. 다음은 초기화의 예입니다.

obj = 1
obj = "foo"

인스턴스화는 매우 다른 것이지만 인스턴스화는 일반적으로 초기화가 뒤 따르기 때문에 관련이 있습니다.

Dim obj As New Object()

In the preceding line of code, the obj variable is initialized with the reference to the new Object that was instantiated. We say that the new Object was instantiated because we have created a new instance of it.

Now I believe that VB.NET makes this a lot more confusing than C# because it is not clear that an assignment is taking place in the code above. In C# it is much clearer that there is both an instantiation of an instance and an initialization of a variable:

Object obj = new Object();

To initialize something is to set it to its initial value. To instantiate something is to create an instance of it.

Often this is the more or less same thing. This:

SqlConnection conn = new SqlConnection();

instantiates a SqlConnection object, and initializes the conn variable by setting it to the that instance.

Since an object's constructor also sets the object's properties to their default values, it's often correct to say that instantiating an object initializes it. (Misleading, if the object exposes a method that you have to explictly call to initialize it after it's instantiated, as is sometimes the case.)


*Instantiation means to create an instance for a class or object.Initialization means to *initiate the same object or class for any purpose.**


Instantiated means that an instance of the object has been created. Initiated means that that same object has done some initialization.


When you instantiate a class or object, you're creating a new instance of it, or allocating memory to "hold" one. Initializing that object would be the instructions that are performed during instantiation.


Instantiation is when you create an instance of a class. That instance is then an object, and you can set its properties, or call methods on it (tell it to do things).

Initiation is when you set up a set of initial conditions for something. That something might be an object, where you tell it to initiate itself, or just a variable to which you assign a value.

An object might initialise some other things, or even instantiate other objects as part of its initiation.

The difference is that instantiation is creation of a thing that can do stuff; initiation is stuff that gets done.


See the Java docs: https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html

"Point originOne = new Point(23, 94);

Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object."

Instantiation refers to the allocation of memory to create an instance of a class whereas initialization refers to naming that instance by assigning the variable name to that instance.

Eg: SqlConnection conn = new SqlConnection();

Here new is a keyword which allocates memory for an instance and conn is a variable name assigned for that instance.


Others have explained the difference, so I wont go into detail. But there are cases where instantiation does not properly initialize an object. When you instantiate an object you also initialize it with some data. The class/type will have the initialization logic, whereas the instantiation logic is typically carried out by thenew keyword (basically memory allocation, reference copying etc). But instantiation need not necessarily result in a valid state for objects which is when we can say the object is uninitialzed. Here's a practical example where an object can be instantiated but not initialized (sorry e.g. in C#).

class P { string name = "Ralf"; }

WriteLine(new P().name); // "Ralf";
WriteLine((FormatterServices.GetUninitializedObject(typeof(P)) as P).name); // null

GetUninitializedObject doesn't call the constructor to instantiate object there (but some internal magic).

One could also argue value types are not instantiated but only initialized as it doesn't need new allocation when you do new.. but that's up to one's definition of instantiation.


We can see it this way. For a line of code below:

var p = new Person();

The above line can be read as following two ways:

  1. The variable p has been initialized as a person class
  2. Person class has been instantiated in variable p

The subject of reference or context matters. When talking in terms of variable, we use the word initialize. When talking in terms of class/type, we use the word instantiate.

참고URL : https://stackoverflow.com/questions/2330767/what-is-the-difference-between-instantiated-and-initialized

반응형