Development Tip

개체와 인스턴스의 차이점

yourdevel 2020. 10. 15. 21:51
반응형

개체와 인스턴스의 차이점


나는 이런 종류의 질문이 전에 물어 본 적이 있다는 것을 알고 있지만 여전히 대답이 너무 모호하여 (그리고 더 나아가 일부 / 대부분의 초보자가) 이해할 수 없다고 느낍니다.

절차 적 및 기본 OOP보다 더 넓은 프로그래밍 개념을 가르치려고 노력해 왔습니다. 저는 OOP의 구체적인 개념을 이해합니다 (데이터 (멤버)와 함수 (메소드)가있는 클래스를 만든 다음 런타임에 해당 클래스를 인스턴스화하여 실제로 작업을 수행합니다).

나는 클래스가 무엇인지에 대한 핸들을 가지고 있다고 생각합니다 ( 컴파일 타임에 인스턴스가 생성되는 일종의 디자인 청사진 ). 하지만 그렇다면 객체 란 무엇일까요? 나는 또한 프로토 타입 기반 언어에서 이것이 더 많은 것을 방해 할 수 있다는 것을 알고 있지만, 아마도 이것이 내 마음 속에서 객체와 인스턴스를 분명하게 구분해야하는 이유 일 것입니다.

그 외에도 "오브젝트"와 "인스턴스"의 개념으로 어려움을 겪습니다. 내가 읽은 많은 리소스 (SO의 답변 포함)는 거의 동일하며 의미론에 차이가 있다고 말합니다. 다른 사람들은 둘 사이에 진정한 개념적 차이가 있다고 말합니다.

SO의 전문가가 초보자가 OOP의 세계에서 앞으로 나아갈 수있는 "아하"순간을 가질 수 있도록 도와 줄 수 있습니까?

다시 한 번 감사드립니다.

참고 : 이것은 숙제가 아닙니다. 저는 학교에 가지 않습니다. 그러나 숙제 도움을 찾는 사람들에게 도움이 될 것이라고 생각합니다.


집 디자인의 청사진은 수업 설명과 같습니다. 그 청사진으로 지어진 모든 집은 그 클래스의 객체입니다. 주어진 집은 예입니다.


사실 객체 지향 프로그래밍은 개발의 철학적 측면과 컴퓨터의 실제 기계 작동 사이의 단절을 만들어 혼동을 일으키는 경우가 많습니다. 나는 당신을 위해 두 가지를 대조하려고 노력할 것입니다.

OOP의 기본 개념은 Class >> Object >> Instance입니다.

클래스 = 청사진. Object는 '청사진'(집과 같은)을 기반으로 만들어진 실제 물건입니다. 인스턴스는 개체의 가상 복사본 (실제 복사본이 아님)입니다.

'인스턴스'에 대한보다 기술적 설명은 '메모리 참조'또는 참조 변수라는 것입니다. 에 '예'가 메모리에 변수가 있음이 수단 그 안에 객체의 메모리 주소가 있습니다. 주소를 지정하는 개체는 인스턴스가 '인스턴스'라고하는 것과 동일한 개체입니다. 객체의 인스턴스가 많은 경우 메모리의 다른 위치에 여러 변수가 있고 모두 동일한 정확한 메모리 주소를 가지고 있습니다. 모두 동일한 정확한 객체의 주소입니다. 코드에서 할 수있는 것처럼 보이지만 인스턴스를 '변경'할 수 없습니다. 인스턴스를 '변경'할 때 실제로하는 일은 원래 객체를 직접 변경하는 것입니다. 전자적으로, 프로세서는 원래 객체의 데이터를 변경하기 전에 메모리 (참조 변수 / 인스턴스)의 한 추가 위치를 통과합니다.

프로세스는 프로세서 >> 인스턴스의 메모리 위치 >> 원래 개체의 메모리 위치입니다.

사용하는 인스턴스는 중요하지 않습니다. 최종 결과는 항상 동일합니다. 모든 인스턴스는 메모리 위치 (객체의 메모리 주소)에서 동일한 정확한 정보를 계속 유지하며 객체 만 변경됩니다.

클래스와 객체 사이의 관계는 철학적으로 이해하기 가장 쉽지만 조금 더 혼란 스럽습니다 (청사진 >> 집). 객체가 메모리 어딘가에 보관 된 실제 데이터 인 경우 '클래스'는 무엇입니까? 기계적으로 객체는 클래스의 정확한 사본이라는 것이 밝혀졌습니다. 따라서 클래스는 객체가 수행하는 것과 동일한 정확한 정보를 보유하는 메모리의 다른 변수 일뿐입니다. 관계 간의 차이점에 유의하십시오.

개체는 클래스 복사본 입니다. 인스턴스는 객체의 메모리 주소를 보유하는 변수입니다.

또한 동일한 클래스의 여러 개체를 보유한 다음 각 개체의 여러 인스턴스를 가질 수도 있습니다. 이러한 경우 각 개체의 인스턴스 집합은 값이 동일하지만 개체 간의 인스턴스는 그렇지 않습니다. 예를 들면 :

클래스 A의 클래스 A가 Object1, Object2 및 Object3을 사용하도록합니다.

// Object1은 object2 및 object3과 동일한 정확한 값을 갖지만 메모리의 다른 위치에 있습니다.

Object1에서 >> let obj1_Instance1, obj1_Instace2, obj1_Instance3

//이 모든 인스턴스는 값과 메모리의 다른 위치에서도 동일합니다. 해당 값 = Object1.MemoryAddress.

기타

유형을 도입하기 시작하면 상황이 더 복잡해집니다. 다음은 C #의 형식을 사용하는 예입니다.

// Person 클래스가 존재한다고 가정 Person john = new Person ();

실제로이 코드를 두 부분으로 나누면 분석하기가 더 쉽습니다.

Person john;
john = new Person();

기술적으로 말하면 첫 번째 줄은 ' 유형 의 변수를 선언 합니다.사람. 하지만 그게 무슨 뜻이야 ?? 일반적인 설명은 이제 Person 객체 만 담을 수있는 빈 변수가 있다는 것입니다. 그러나 잠깐만-빈 변수입니다! 해당 변수 메모리 위치에는 아무것도 없습니다. '유형'은 기계적으로 무의미한 것으로 밝혀졌습니다. 유형은 원래 데이터를 관리하기위한 방법으로 만들어졌습니다. int, str, chr (초기화없이)와 같은 기본 유형을 선언하더라도 컴퓨터 내에서 아무 일도 일어나지 않습니다. 프로그래밍의이 이상한 구문 적 측면은 사람들이 클래스가 객체의 청사진이라는 아이디어를 얻는 부분입니다. OOP는 델리게이트 유형, 이벤트 핸들러 등이있는 유형과 훨씬 더 혼동을 일으켰습니다. 나는 그것들에 너무 집중하지 않고 모두 잘못된 이름이라는 것을 기억할 것입니다.

두 번째 줄도 한 번에 두 가지 작업을 수행하기 때문에 약간 혼란 스럽습니다.

오른쪽 "new Person ()"이 먼저 평가됩니다. Person 클래스의 새 복사본을 만듭니다. 즉, 새 개체를 만듭니다.

그런 다음 왼쪽 "john ="이 평가됩니다. john을 참조 변수로 바꾸어 같은 줄의 오른쪽에 방금 생성 된 객체의 메모리 주소를 제공합니다.

좋은 개발자가되고 싶다면 철학적 이상을 기반으로 작동하는 컴퓨터 환경이 없다는 것을 이해하는 것이 중요합니다. 컴퓨터는 그다지 논리적이지 않습니다. 실제로는 기본 부울 회로 (주로 NAND 및 OR)를 사용하여 서로 붙어있는 큰 전선 모음 일뿐입니다.


단어 클래스 에서 온다 분류 ( 카테고리 뭔가가 투입되는 지금 우리는 모두가 들었습니다) 클래스는 청사진 유사하지만, 무엇이 정확히 의미? 즉, 클래스 가 특정 카테고리에 대한 설명을 보유하고 있음을 의미합니다. ( Java를 사용하여 예제로 Class, Object 및 Instance의 차이점을 보여주고 싶습니다. 읽는 동안 독자에게 스토리처럼 시각화하도록 요청합니다. 중요하지 않습니다 자바에 익숙하지 않은 ) 그래서 우리가 저지르는 시작하자 카테고리 이라고 HumanBeing 다음과 같이 자바 프로그램을 표현 있도록,

class HumanBeing{ 
   /*We will slowly build this category*/ 
}

이제 HumanBeing 은 일반적으로 Name , Age , Height , Weight 에서 어떤 속성을 가지고 있는지 지금은 우리의 자아를이 네 가지 속성으로 제한하고 카테고리에 추가하겠습니다.

class HumanBeing{
    private String Name;
    private int Age;
    private float Height;
    private float Weight; 

   /*We still need to add methods*/

}

이제 모든 카테고리 예 범주에 대한 행동이 개는 껍질에 행동이를, 등등 ..., 마찬가지로 우리의 카테고리, 롤을 가져 HumanBeing은 또한 예를 들어 우리가 요청하는 경우, 특정 동작을 할 수 HumanBeing은 당신의 이름 / 나이 / 체중 것입니다 / 신장? 이름 / 연령 / 체중 / 높이를 제공해야하므로 자바에서는 다음과 같이합니다.

class HumanBeing{
    private String Name;
    private int Age;
    private float Height;
    private float Weight;  

    public HumanBeing(String Name,int Age,float Height,float Weight){
       this.Name = Name;
       this.Age  = Age;
       this.Height = Height;
       this.Weight = Weight;
    }

    public String getName(){
      return this.Name;
    }

    public int getAge(){
      return this.age;
    }

    public float getHeight(){
      return this.Height;
    }

    public float getWeight(){
      return this.Weight;
    }
}

이제 우리는 HumanBeing 범주에 행동을 추가 했으므로 이름, 나이, 키, 몸무게를 물어볼 수 있지만 이러한 세부 정보를 누구에게 물어 보시겠습니까?class HumanBeing 범주 일 뿐이 므로 청사진입니다. 예를 들어 건축가가 청사진을 작성합니다. 그가 만들고자하는 건물의 종이, 이제 우리는 청사진 ( 건물에 대한 설명) 에서 살 수 없습니다. 우리는 건물이 지어진 후에 만 ​​살 수 있습니다. 그래서 여기서 우리는 우리의 범주에서 인간을 만들어야합니다. 위에서 설명 했으므로 Java에서 어떻게 수행합니까?

class Birth{
  public static void main(String [] args){
    HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);    
  }
}

이제 위의 예에서 우리는 age height weight라는 이름을 가진 첫 인간을 만들었습니다. 그렇다면 위 코드에서 정확히 무슨 일이 일어나고 있습니까? . 우리는 HumanBeing 범주를 인스턴스화 하고 있습니다. 즉, 클래스의 객체가 생성됩니다.

참고 : 객체와 인스턴스는 동의어가 아닙니다 . 어떤 경우에는 객체와 인스턴스가 동의어 인 것처럼 보이지만 그렇지 않습니다. 두 경우 모두 제공합니다.

사례 1 : 개체 및 인스턴스 동의어 것 같다
우리가 말할 때,하자 나를 조금 정교한 HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90); object를 우리의 카테고리가 만들어집니다 힙 메모리 및 일부 주소가 할당되고, firstHuman그 주소에 대한 참조를 보유하고, 지금이 개체입니다 HumanBeing의 객체HumanBeing의 인스턴스 . 여기서는 객체와 인스턴스가 동의어 인 것 같습니다. 나는 동의어가 아닙니다.

우리의 이야기를 재개합시다, 우리는 우리의 firstHuman을 만들었습니다. 이제 우리는 그의 이름, 나이, 키, 몸무게를 물어볼 수 있습니다. 이것이 우리가 자바에서하는 방법입니다.

class Birth{
  public static void main(String [] args){
    HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
    System.out.println(firstHuman.getName());
    System.out.println(firstHuman.getAge());
    ...
    ...  
  }
}

우리가 처음 인간의 존재가 어떤 자격있는 우리의 첫번째 인간을 제공하여 이동 깃털을 할 수 있도록, 우리라는 범주가 필요하므로 그 의사가하게하자 의사를 그래서 자바에서 우리가 다음 할, 우리의 의사에게 몇 가지 동작을 제공

class Doctor extends HumanBeing{
   public Doctor(String Name,int Age,float Height,float Weight){
      super(Name,Age,Height,Weight);
   }
   public void doOperation(){
    /* Do some Operation*/ 
   }

   public void doConsultation(){
    /* Do so Consultation*/
   }
}  

여기서 우리는 코드에서 재사용 성을 가져 오는 상속 개념을 사용했습니다 . 모든 의사는 항상 인간이 먼저이기 때문에 의사는 이름, 나이, 몸무게, 키를 다시 작성하는 대신 HumanBeing에서 상속 될 것입니다. 아직 만들지 않은 의사에 대한 설명을 방금 작성 했으므로class Birth

class Birth{
  public static void main(String [] args){
    Doctor firstDoctor = new Doctor("Strange",40,6,80);
    .......
    .......
    /*Assume some method calls , use of behaviour*/
    .......
    .......    
  }
}

사례 2 : 객체와 인스턴스가 동의어가 아닙니다
. 위 코드에서 Doctor 범주를 인스턴스화하고 생명력을 불어 넣고 있음을 시각화 할 수 있습니다. 즉, 단순히 Doctor 범주의 객체를 생성하고 있습니다. 이미 알고 있듯이 객체가 힙 메모리에 생성된다는 것을 알고 있습니다. firstDoctor힙의 해당 개체에 대한 참조를 보유하고;

이 특정 객체 firstDoctor는 다음과 같습니다 ( firstDoctor객체 자체가 아니라 객체에 대한 참조를 보유하고 있습니다)

  1. firstDoctor이다 의 객체class Doctor 그리고 (A)의 인스턴스class Doctor
  2. firstDoctor이다 의 아닌 개체class HumanBeing 그러나 의 인스턴스class HumanBeing

따라서 특정 개체는 특정 클래스의 인스턴스가 될 수 있지만 해당 클래스의 개체 일 필요는 없습니다.

결론:

객체는 특정 범주의 모든 특성을 충족하는 경우 특정 범주의 인스턴스라고합니다.

현실 세계의 예는 다음과 같을 것입니다. 우리는 인간으로 처음 태어 났으므로 우리를 인간의 대상으로 이미지합니다. 이제 우리는 성장할 때 책임을지고 새로운 기술을 배우고 삶의 예에서 다른 역할을 수행합니다 아들, 형제, 딸, 아버지 , 어머니 이제 우리는 실제로 무엇입니까? 우리는 인간의 대상이지만 형제, 딸 등의 인스턴스라고 말할 수 있습니다.

이게 도움이 되길 바란다

감사합니다


여기에 이미지 설명 입력

객체는 메모리에있는 사물이고 인스턴스는이를 참조하는 사물입니다. 위의 그림에서 :

  • std (instance)-> Student Object (오른쪽)
  • std1 (인스턴스)-> Student Object (왼쪽)
  • std2 (인스턴스)-> Student Object (왼쪽)
  • std3 (인스턴스)-> 객체 없음 (null)

객체는 클래스의 인스턴스입니다 (클래스 기반 언어의 경우).

I think this is the simplest explanation I can come up with.


A class defines an object. You can go even further in many languages and say an interface defines common attributes and methods between objects.

An object is something that can represent something in the real world. When you want the object to actually represent something in the real world that object must be instantiated. Instantiation means you must define the characteristics (attributes) of this specific object, usually through a constructor.

Once you have defined these characteristics you now have an instance of an object.

Hope this clears things up.


"A class describes a set of objects called its instances." - The Xerox learning Research Group, "The Smalltalk-80 System", Byte Magazine Volume 06 Number 08, p39, 1981.


What is an Object ?

An object is an instance of a class. Object can best be understood by finding real world examples around you. You desk, your laptop, your car all are good real world examples of an object.

Real world object share two characteristics, they all have state and behaviour. Humans are also a good example of an object, We humans have state/attributes - name, height, weight and behavior - walk, run, talk, sleep, code :P.

What is a Class ?

A class is a blueprint or a template that describes the details of an object. These details are viz

name attributes/state operations/methods

class Car 
{
    int speed = 0;
    int gear = 1;

    void changeGear(int newGear)
    {
        gear = newGear;
    }

    void speedUp(int increment) 
    {
        speed = speed + increment;
    }

    void applyBrakes(int decrement) 
    {
        speed = speed - decrement;
    }
}

Consider the above example, the fields speed and gear will represent the state of the object, and methods changeGear, speedUp and applyBrakes define the behaviour of the Car object with the outside world.

References:


I think that it is important to point out that there are generally two things. The blueprint and the copies. People tend to name these different things; classes, objects, instances are just some of the names that people use for them. The important thing is that there is the blueprint and copies of it - regardless of the names for them. If you already have the understanding for these two, just avoid the other things that are confusing you.


I guess the best answer has already been given away.

Classes are blueprints, and objects are buildings or examples of that blueprint did the trick for me as well.

Sometimes, I'd like to think that classes are templates (like in MS Word), while objects are the documents that use the template.


Lets compare apples to apples. We all know what an apple is. What it looks like. What it tastes like. That is a class. It is the definition of a thing. It is what we know about a thing.

Now go find an apple. That is an instance. We can see it. We can taste it. We can do things with it. It is what we have.

Class = What we know about something. A definition.

Object/Instance = Something that fits that definition that we have and can do things with.


In some cases, the term "object" may be used to describe an instance, but in other cases it's used to describe a reference to an instance. The term "instance" only refers to the actual instance.

For example, a List may be described as a collection of objects, but what it actually holds are references to object instances.


I have always liked the idea that equals the definition of a class as that of an "Abstract Data Type". That is, when you defined a class you're are defining a new type of "something", his data type representation, in terms of primitives and other "somethings", and his behavior in terms of functions and/or methods. (Sorry for the generality and formalism)

Whenever you defined a class you open a new possibility for defining certain entities with its properties and behavior, when you instantiate and/or create a particular object out of it you're actually materializing that possibility.

Sometimes the terms object and instances are interchangeable. Some OOP purists will maintain that everything is an object, I will not complain, but in the real OOP world, we developers use two concepts:

  1. Class: Abstract Data Type sample from which you can derive other ADT and create objects.
  2. Objects: Also called instances, represents particular examples of the data structures and functions represented by a given Abstract Data Type.

Object Oriented Programming is a system metaphor that helps you organize the knowledge your program needs to handle, in a way that will make it easier for you to develop your program. When you choose to program using OOP you pick up your OOP-Googles, and you decide that you will see the problem of the real world as many objects collaborating between themselves, by sending messages. Instead of seeing a Guy driving a Car you see a Guy sending a message to the car indicating what he wants the car to do. The car is a big object, and will respond to that message by sending a message to it's engine or it's wheel to be able to respond properly to what the Driver told him to do in the message, etc...

After you've created your system metaphor, and you are seeing all the reality as objects sending messages, you decide to put all the things your are seeing that are relevant to your problem domain in the PC. There you notice that there are a lot of Guys driving different cards, and it's senseless to program the behavior of each one of them separately because they all behave in the same way... So you can say two things:

  • All those guys behave in the same way, so I'll create a class called Driver that will specify who all the Drivers in the world behave, because they all behave in the same way. (And your are using class based OOP)
  • Or your could say Hey! The second Driver behaves in the same way as the first Driver, except he likes going a little faster. And the third Driver behaves in the same way as the first Driver, except he likes zigzagging when he drives. (And you use prototype based OOP).

Then you start putting in the computer the information of how all the Drivers behave (or how the first driver behave, and how the second and third differ from that one), and after a while you have your program, and you use the code to create three drivers that are the model you are using inside that PC to refeer to the drivers you saw in the real world. Those 3 drivers that you created inside the PC are instances of either the prototype ( actually the first one is the prototype, the first one might be the prototype himself depending on how you model things) or the class that you created. The difference between instance and object is that object is the metaphor you use in the real world. You choose to see the guy and the car as objects (It would be incorrect to say that you see them as instances) collaborating between themselves. And then you use it as inspiration to create your code. The instance only exists in your program, after you've created the prototype or the class. The "objects" exist outside the PC because its the mapping you use to unite the real world with the program. It unites the Guy with the instance of Driver you created in the PC. So object and instance are extremely related, but they are not exactly the same (an instance is a "leg" of an object in the program, and the other "leg" is in the real world).


Extending one of the earlier given examples in this thread...

Consider a scenario - There is a requirement that 5 houses need to be built in a neighbourhood for residential purposes. All 5 houses share a common construction architecture. The construction architecture is a class. House is an object. Each house with people staying in it is an instance.


Object:when ever we create an object some memory is occupied by that Object Ex: Test t=new Test();//here t is an object of Test class

Instance:When ever we Declare the Instance separate memory is not occupied by that instance Ex: Test t;//here t is the instance of Test class


Simply say that object is a only declaration which do not allocate memory. and instance is a object of a class which allocates the memory.


나에게 객체와 인스턴스 사이에는 작은 차이가 있습니다.

처럼 :

class1 obj;

여기서 obj는 스택 메모리를 차지하는 class1의 인스턴스입니다.

class1 obj = new class1 ();

이 경우 obj는 class1의 객체이며 힙 메모리를 차지합니다.

참고 URL : https://stackoverflow.com/questions/3323330/difference-between-object-and-instance

반응형