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 I'm missing?
In Object Oriented Programming or OOP we must distinguish two different concepts:
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 going to be created in the dynamic memory (heap) or in the program stack (stack):
However, this does not have to be the case in all languages since each one has its own characteristics and object-oriented programming theory is independent of the language used.
The instance of a class is the object which from the moment of its existence; is able to access:
Depending on the access modifier they have
public
private
protected
Let's also remember that the instance gives us the ability to assign values that the class might be expecting to receive and manipulate via its internal constructor method.
We resort to this process because having a class like this:
It only represents:
But so to speak, the class there is not able to speak and display its content; at least not until the object that represents it receives possible values for its constructor method and consequently can access the actions or verbs it contains.
However, to have an object that represents the class, it is not strictly necessary to use the instance; not at least with the common structure.
We can make use of
static factory method
, as I am not skilled in Java so I leave you an example in PHP but it should also give you an idea of how:protected
to the constructor methodstatic
to not depend directly on the instance outside the class, like this:example code:
Which gives us the following output:
Look at the following example:
In both cases we observe the following result:
In both cases we observe that we obtain an instantiated object of the Demo class both in the regular way and also by means of the return of an instance within a static method.
Interesting reading and references