Hi to the whole community. I have written this POST in order to improve the understanding of class and instance variables . I have searched the Internet, and what has become clear to me is that:
- A class variable is when it is written as static , which is declared in fields as static in constructors and methods. Also, class constants would be static final .
- An instance variable doesn't carry anything special, just that it's created as an object, that object is instantiated, and used in a method, in that order.
I don't know if I have interpreted it correctly or if I need something more to know or understand and if I have interpreted correctly what I have written before.
When you declare static variables in a class you can access them from anywhere without creating an object from it. For example:
You call static variables with the name of the class and a period, and the name of the variable or function. To access variables of the object (the non-static ones), we must instantiate an object of it and access its variable or function.
First it is necessary to point out that the Java language specification is quite exact in the terms it uses, and in particular the word member is not used. We always talk about variables that belong to a class, an object or a method.
Referring to the specification we find the following:
Class variables belong to the class definition. To define one, the keyword is used
static
as a modifier.The variable
total
is shared by all objects of typeCar
that are created:Every time I create an object of type I
Car
increase the variabletotal
(number of objects created) by one, since the variable is shared by all objects (because it belongs to the class definition), when in principle one could think of a variable class as a 'global variable. Since the definition of the variable belongs to the class, it is possible to access it without using an object reference, so this is absolutely valid:we access the variable through the class name and not through some reference to an object.
Instance variables are those that are declared in a class but without the reserved word
static
Unlike class variables, ownership and responsibility for these belongs to each object that is created. For example:
In other words, instance variables are the responsibility of each instance of a class, so each has its own copy of the variable, and changing the value of an instance variable in the object will
libro1
not change the value of the same variable. instance with the same name in the objectlibro2
This video explains class variables and instance variables: https://www.youtube.com/watch?v=SLyl1OO7CzQ