Difference between Object and Instance

Asked

Viewed 13,505 times

23

Object-oriented programming is often spoken of in both class and object instances. Seeking the meaning of each one, I realized that now the concepts are unified and the same are treated as synonyms, now the concepts differ and the same are treated differently.

Wikipedia’s own page shows this confusion: in the definition of instance brings that it is "an object whose behavior and state are defined by the class"; already in the definition of object brings that "object refers to an instance of a class". The instance is an object and the object is an instance? Then it would be the same thing?

In a book on object orientation there is the definition for object:

Object (also known as object instance or instance) is an individual instance of the data structure defined by the class.

Which implies that the concepts of object and instance are the same.

In turn, in this reply on the meaning of "object-oriented" is cited:

The object is an instance of the class and the instance accesses the predefined behaviors.

Implying that the object is an instance, but the concepts are not equivalent, since it would be the instance responsible for access to class behaviors.

Then, in the end, instance and object are synonymous or are different things but are directly related to each other to the point of commonly being considered equivalent?


Other references:

  • (1) "In OOP an instance of a class is called an object".
  • (2) "Each element of a class is known as an object or instance of that class".
  • (3) "MARTIN 1994: An object is an instance of an object type".
  • (4) "Instance: An individual Object of a Certain class".
  • (5) "Object: A Unique instance of a data Structure that’s defined by its class".
  • (6) "[...] an Object represents an instance".
  • (7) "[..] Objects are instantiated from a class, and each Object is referred to as an instance of the class".
  • An individual Object of a Certain class = 1 single item of a class... if I have a group of people... the object is people... and the instance is Daniel... Anderson... Joao... instance is 1 unique created object of the class... if I have 10 feet of lime ... the object is the lemon foot, and each lime foot is an instance of the lemon foot type Not that they are equal, object refers as the whole and instance is specifically where that class, that object appears... basic example would look like this: Model model; Model = object and model = instance of the Model class

  • In programming, or in programs, it would look something like this: Object -> characterizing properties. Instance -> Existence, or even the materialized form. Color of a Car, Engine Type, Number of Wheels would be basically the object itself, and "A Car" would be an instance of that object.

  • 1

    In this phrase that the PA cited did not understand where is the difference between the two: "The object is an instance of the class and the instance accesses the predefined behaviors". If an object is an instance as the phrase states, one can substitute instance for object and so is "the object accesses the predefined behaviors". No differentiation here.

5 answers

12


Your reference 3 is a super accurate and correct definition:

"An object is an instance of an object type".

You see right away that instance is the technical thing that allows the existence of an object in memory. The word Object, in turn, can be used at a higher level of abstraction.

See: the word "object" exists because the concept of Object Orientation is to represent in the software the relevant characteristics and behaviors of the real objects of the domain.

So when modeling a system of fiscal notes, the notes and their items are objects; and when coding the system, classes will be declared to define these objects, and for these objects to exist in memory will be created instances of these classes.

class NotaFiscal; // não é objeto nem instância, é a definição de um objeto.
var notaFiscal = new NotaFiscal; // "notaFiscal" referencia uma instância
notaFiscal.setNumero(1234);      // a instância representa a Nota Fiscal 1234, 
                                 // que é um objeto de domínio 
                                 // e existe como objeto para além do código fonte.

After the objects are persisted the instances are removed from memory and the objects as we know them in the real world will be safe in the database until we need to deal with them again - and then again we will create instances of your classes to be able to look at these beautiful objects and manipulate them.

And if objects are persisted in an object-oriented database, objects continue to exist in the technical realm beyond the conceptual even after their instances no longer exist in memory.

Finally, instance and object are interchangeable terms, as in this hypothetical but correct dialogue:

_ I recovered all the tax notes from the base and got this array of 1000 objects.

_ It would be better not to have so many instances at once in memory because otherwise the system will be slow, since Invoice is a kind of large object.

_ Ok. Then I will make a pagination to keep only 10 objects at a time in the array.

  • Good answer, I just found it a little confusing to say that objects are persisted when in fact what is persisted is only the state of them (considering that objects are composed of state + behavior).

  • 1

    @Piovezan does not disagree with you, this is a way of saying too. To say that the object itself is persisted is an expression of a higher level of abstraction. And if we persist with the state of the object in order to be able to reconstitute the object in memory later again, then it doesn’t make much difference if we say it is the object or if we say it is the state of it that is persisted.

10

You have a class A that can be instantiated n times, generating a group of n objects of type Class A. If you take one of these objects individually, you are dealing with an instance of A. The fonts, for the most part, really treat object and instance interchangeably. Keep in mind that the instantiation of a class A will give rise to an object of the same class. (Being simplistic here, okay? Discarding more advanced concepts such as inheritance, polymorphism, etc.)

inserir a descrição da imagem aqui

  • Then instance would be the abstraction of the object?

  • 2

    I prefer to think of it as an instance being the "materialization" of the class, which generates an object in memory. Something with which you can interact. ;)

4

The instance is an object and the object is an instance? Then would the same thing?

Yes and no.

On the Wikipedia page itself there are 3 paragraphs that speak the same thing in different ways. It is redundant but they did so to clarify better.

Instances of a class share the same set of attributes, although they differ as to the content of those attributes. For example, the "Employee" class describes the attributes common to all instances of the "Employee" class. The objects of this class may be similar, but vary in attributes such as "name" and "salary". The class description contains the items corresponding to those attributes and defines the operations or actions relevant to the class such as "salary increase" or "change in the number of phone". One can then talk about an instance with the name = "Joana Rabbit" and another with the name = "João Coelho".

Instance is the embodiment of a class. Intuitively, a class is like a "mold" that generates instances of a certain type; a object is something that exists physically and has been "shaped" in the class.

Thus, in object-oriented programming, the word "instantiation" means to create. When we speak of "instantiating an object", we create physically a concrete representation of the class. For example: "animal" is a class or a mold; "dog" is an instance of "animal" and despite carrying all the mold characteristics of "animal" is completely independent from other instances of "animal" https://pt.wikipedia.org/wiki/Inst%C3%A2ncia_(class)

// Aqui temos uma classe. Ela ainda não é um objeto.
Class Foo{}

// Aqui criamos um objeto da classe Foo
obj = new Foo

// Repare que não usei o termo "instância" porque esse termo significa "criar". Contudo, não é errado dizer:

// Nova instância de Foo
obj = new Foo

That is, the obj is a objeto instantiated from the class Foo.

Instance (instantiating/creating) is an action. The object is a concrete representation, according to wikipedia, we create (instantiation) physically a class representation.

The definition of what the object is also very clear and I see no ambiguity:

In computer science, object is a reference to a memory that has a value. An object can be a variable, function, or data structure. With the introduction of objects, the word object refers to an instance of a class.

In object-oriented programming, an object comes into existence from of a "mold" (class); the class defines the behavior of the object, using attributes (properties) and methods (actions). https://en.wikipedia.org/wiki/Object_(computer_science)

Important to note that still on the Wikipedia page brings an observation on the term instance.

In object-oriented programming, it’s called a class instance, an object whose behavior and state are defined by the class. "Instance" is, in this case, a anglicism, meaning "case" or "example" (in English instance).

Anglicism: https://en.wikipedia.org/wiki/Anglicism

Not to complicate matters, I’ll avoid commenting on Metaclass because it escapes a little from the context of the question. But anyway it is good to know.

The theme is covered in the Japanese version of "Instance": https://ja.wikipedia.org/wiki/%E3%82%A4%E3%83%B3%E3%82%B9%E3%82%BF%E3%83%B3%E3%82%B9

静的型付けのオブジェクト指向言語では珍しいが、動的型付けのオブジェクト指向言語の多くは、メタクラスをサポートし、クラス自体もオブジェクトとして扱うことができる(クラス・オブジェクト)。 クラス・オブジェクトは、端的に言えば変数に束縛できるクラスである。 クラス・オブジェクト、インスタンス・オブジェクト双方を変数に束縛した際どちらもオブジェクトとして振る舞い見かけ上区別はつかない。 例えばクラス・オブジェクト、インスタンス・オブジェクト双方が readFrom: というメソッドを持っていた場合、どちらも #readFrom: メッセージを送ってやるとエラーも起こさずそれぞれのメソッドを実行する。 Objective-CやPythonにおいてはクラス・オブジェクトとインスタンス・オブジェクトの明確な区別が行われている。 [3][4] メタクラスがサポートされているシステムでは、クラス・オブジェクトもまた別のクラス(メタクラス)のインスタンスであるということがありうる。 この場合「クラス・オブジェクトはインスタンスではない」とは言えないので、注意されたい。

This is a brief warning that says not to confuse instances of metaclasses because in metaclasses instances are also classes.

As you can see, we can always complicate even more.

2

Imagine that classes are like the plan of a house, and it defines the shape of the house on paper, the house doesn’t exist yet, but we already have the structure to create a house.

An Object is the house already built according to the plan. The data stored in the object are with wood hardware wires and concrete used to compose the house.

Inside the object we have:

Attributes is what defines the object as color, window type, door type, number of cars etc.

Methods is what defines what the house will do, example is open garage, open windows, turn on lights.

So when you create an object you make an instance of it, which is the action of assigning the characteristics to a variable.

 Curso Completo de Desenvolvimento Web - Crie 6 projetos

Practical example:

//Objeto
class Casa {

    //Atributos

    var $cor;
    var $tipo_de_janela;
    var $tipo_de_porta;


    //Métodos

    function setCor($cor_definido){
        $this->cor = $cor_definido;
    }

    function getCor(){
        return $this->cor;
    }

}

//Instanciando os atributos e métodos do objeto Casa à variável casa número 1, aqui é aonde recebemos os atributos e métodos através do instanciamento no qual poderemos fazer modificações únicas nas variásveis.

$casa_numero_1 = new Casa();

$casa_numero_1->setCor('Laranja<br>');
echo $casa_numero_1->getCor();


$casa_numero_2 = new Casa();

$casa_numero_2->setCor('Branca<br>');
echo $casa_numero_2->getCor();

,

In short: The instance is the ACTION of inheriting methods and attributes to variables. So my instance casa_numero_1 and casa_numero_2 share the same set of attributes, although they are different as to the contents of these attributes one is orange and the other is white.

  • 2

    Could you elaborate further? The simplified form of the answer was unclear.

  • 2 years later is somewhat complicated, but in your answer you say that casa_numero_1 and casa_numero_2 are instances, but would not be objects? If "instance" is an action, as you say, there are no variables like instances, they could be, at most, the result of this action - what would be the result of the instance? The question is precisely about object vs instance and even in the answer you seem to mix the two concepts, so it got confused.

-3

Example: Person person = new Person();

new person(); Instance (is allocating space in memory).

person object;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.