I have a class defined with the following attributes or variables of type id and string
public class Order{
private int id = 9;
private string latitudeCustomer = "123211";
private string longitudeCustomer = "123421";
public Order(string lat,string long){
latitudeCustomer = lat;
longitudeCustomer = long;
}
public void printOrder(){
Console.WriteLine($"{id}{latitudeCustomer}{longitudCustomer}");
}
}
Then in the main method, I create a variable of the class type to store an object of that type:
After storing the object of that type, I call the method that has that object...then the method can read the variables of the class...just as I can create another variable of type Order and call the method.
It can be said that the two variables have different values... both execute the method and for each object, the values that were passed as arguments to the constructor are printed, when instantiating each one.
class Program{
public static void main(string[] args){
Order o0 = new Order("45","67");
Order o1 = new Order("12","14");
o1.printOrder(); //imprime 9 12 14
o0.printOrder(); //imprime 9 45 67
}
}
In this case, the constructor assigns values to the class variables twice. but the two pairs of values persist, not a single value is held and I was wondering how that was possible. if I did publish those variables and through o0
I do this o0.latitudeCustomer = 98;
the 98 is only printed when I execute the method through o0
but o1
if I read the value of that same variable it always remains the same without being overwritten even though o0
latitudeCustomer
the value was assigned 98
through the variable defined in the class.
In simple terms, classes are like recipes that tell the framework how to create the objects.
Every time you make
new Order(...)
ornew CualquierClase(...)
are creating a new instance of that class and what happens is that the framework uses a different memory space to store its content without sharing it with other objects even if they are of the same type (unless it has static members ). ( I repeat that it is a very simplified explanation )According to your example:
o0
ando1
they are two instances of the same class, each one occupies different memory spaces and neither has access to the values of the other.It's like having two cars of the same make and model. Both were created with the same recipe (two instances of the same class) but they may have different colors, they may have traveled different number of kilometers and the amount of gas in their tanks may be different (to name a few properties).
Note that you can also declare static classes or classes with static members (
static ...
), and this question and its answers can serve as a starting point for research on that.