Language: EN

que-es-una-clase-y-una-instancia-programacion

What is a class and an instance

When working with Object-Oriented Programming (OOP), there are three words you will constantly use: OBJECTS, CLASS, and INSTANCE.

Don’t worry, you will get used to them almost effortlessly and use them constantly. But, logically, we need to explain them (because besides programming well, it’s also important to speak well)

Let’s start with OBJECTS. As we already know, they are the foundation of Object-Oriented Programming. We have already explained what objects are in this article.

As a quick reminder, an OBJECT is a way to model a part of reality. The object contains:

  • State, through fields
  • Behavior, through methods

And also, to be a “real” object, it must be treated by your program with certain considerations or “specific rules.” Some of these are:

With this refreshed, let’s explain the concepts of class and instance.

Class

A CLASS is the formal definition of our Object. We can think of it as a “mold” or template for creating objects.

In the Class, we define the properties and methods that the objects created from the class will have.

curso-poo-clase

We will see this more easily with a simple example. Suppose you want to create a program that works with people (for example, to maintain a list of students in a classroom, to buy things, for whatever you want).

The class Person contains the definition of “what a Person has.” Let’s assume that in your program, a person is simply “something” that has:

  • name, which is a string
  • age, which is an integer.

Additionally, your Person can introduce themselves (how nice of them). For which it has a method that displays a message on the screen using the values of the fields name and age.

Let’s see how this would be done in different programming languages,

public class Person {
    // Fields or properties
    public string name;
    public int age;
    
    // Method
    public void Introduce() {
        Console.WriteLine($"Hello, my name is {name} and I am {age} years old.");
    }
}
class Person {
public:
	// Fields or properties
    string name;
    int age;

    // Method
    void introduce() {
        cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl;
    }
};
class Person {
	// Fields or properties
    constructor() {
        this.name = "";
        this.age = 0;
    }

    // Method
    introduce() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}
class Person:
	# Fields or properties
    def __init__(self):
        self.name = ""
        self.age = 0

	# Method
    def introduce(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

Instance

Once we have defined a CLASS, we can start creating objects from the “mold” it defines.

An instance is each of the elements created according to a class.

Each INSTANCE is an independent element that has its own values for the properties defined in the class.

Moreover, of course, you can have multiple instances created from a class (in fact, it’s normal to have several instances of a class).

Now let’s see this with some examples in the main programming languages. In the following codes, we create two instances of the Person class:

  • One for Luis, who is 30 years old
  • Another for Maria, who is 20 years old.

Additionally, we call the Introduce method of each instance to print a message to the console introducing themselves cordially (with their respective names and ages).

// Create an instance of the Person class
Person personLuis = new Person();
personLuis.name = "Luis";
personLuis.age = 30;

// Call the Introduce method
personLuis.Introduce();

// Create another instance of the Person class
Person personMaria = new Person();
personMaria.name = "Maria";
personMaria.age = 20;

// Call the Introduce method
personMaria.Introduce();
// Create an instance of the Person class
Person personLuis;
personLuis.name = "Luis";
personLuis.age = 30;

// Call the Introduce method
personLuis.introduce();

// Create another instance of the Person class
Person personMaria;
personMaria.name = "Maria";
personMaria.age = 20;

// Call the Introduce method
personMaria.introduce();
// Create an instance of the Person class
const personLuis = new Person();
personLuis.name = "Luis";
personLuis.age = 30;

// Call the Introduce method
personLuis.introduce();

// Create another instance of the Person class
const personMaria = new Person();
personMaria.name = "Maria";
personMaria.age = 20;

// Call the Introduce method
personMaria.introduce();
# Create an instance of the Person class
personLuis = Person()
personLuis.name = "Luis"
personLuis.age = 30

# Call the Introduce method
personLuis.introduce()

# Create another instance of the Person class
personMaria = Person()
personMaria.name = "Maria"
personMaria.age = 20

# Call the Introduce method
personMaria.introduce()

As we can see, each of the instances is independent of the others and has its own data. In the example, each Person has its own name and its own age.

Moreover, when they call the Introduce method, they access their own values. Each instance is, wrapped and independent, with its own data.

Best Practices Tips

Now some comments and general thoughts.

There is no single correct way

First, let it be clear that there is no single way to model a person. For you, it may have name and age. But for another, it may have name, birth date, and ID number.

Some ways may give you fewer problems than others at some point. For example, age is probably not a good idea because it changes every year. You will probably have fewer problems with birth date in the future.

However, still, there is no single correct way. What you include or do not include will depend on your needs and those of your project. And a little bit of “extra cleverness” about what will cause problems at some point.

The word “object”

Another special bonus to talk about the word “Object.” Initially, the concepts OBJECT, CLASS, and INSTANCE are related concepts but different.

On one hand, CLASS and INSTANCE represent very different things. Here there is no doubt about their use. The class is the “mold,” and the instance is “what you create” with that mold.

But regarding the word “Object”… ñieee. When you are day-to-day talking with other programmers, you will end up using it to refer to both class and instance.

For example, sometimes you will say “we need to create a student object.” And in reality, here you are referring to creating a Student class. But other times you will say “this object here is giving me a problem,” and there you are probably referring to an instance.

In the end, don’t obsess over it; words are just words. What matters is to understand the concepts well and that when you talk to someone, you understand each other.