java – What is an instance in OOP?

Question:

I've been programming for a long time and whenever I read or hear the words instance or instantiate, I get an idea of ​​what is being talked about but I'm not entirely sure.

I understand that the instance of an object is when we create a new object and reserve a space for it in memory:

Object obj = new Object();

I'm right? I forgot something? Is there a piece of information that I am missing?

Answer:

In Object Oriented Programming or OOP, two different concepts must be distinguished:

  • class : A class is a prototype or template that indicates what characteristics are going to have and how the elements created from said class are going to behave.
  • object : Objects are the elements created from the aforementioned classes. In some contexts or languages ​​the term instance is also used

That is, from a class you can create infinite objects or instances.

Note that the previous definitions do not indicate where or how the object or instance is to be created and that is an irrelevant aspect in this case. In languages ​​like C ++, for example, you have the ability to choose whether the object is to be created in the dynamic memory (heap) or on the program stack (stack):

class POO
{
  // ...
};

int main()
{
  POO a; // a se crea en el stack
  POO* b = new POO; // b se crea en el heap.

  delete b; // La memoria dinámica es necesario liberarla.
}

However, this does not have to be the case in all languages ​​since each one has its own characteristics and the theory of object-oriented programming is independent of the language used.

Scroll to Top