What is a class variable and an instance variable?

6

Good to the whole community. I have written this POST with the aim of improving understanding about class and instance variable . I searched the Internet, and what has been clear to me, is that:

  • A class variable is when it is written as static , which is declared in fields such as static in constructors and methods. In addition, the class constants would be static final .
  • An instance variable does not have anything special, only that it is created as an object, that object is instantiated and used in a method, in that order.
  • I do not know if I have interpreted it well or if I need something more to know or understand and if I have interpreted well what I have written before.

        
    asked by Anónimo 28.01.2017 в 00:04
    source

    2 answers

    7

    When you declare static variables in a class you can access them from anywhere without creating an object from it. For example:

    public class Persona{
      static public String nombreEstatico = "Nombre Estatico";
      public String nombreMiembroClase = "Nombre Miembro de la clase";
    }
    public class Main{
      static public main(String[] args){
      System.out.println(Persona.nombreEstatico);
      Persona persona = new Persona();
      System.out.println(persona.nombreMiembroClase);}}
    

    Static variables are called with the name of the class and a period, and the name of the variable or function. To access object variables (non-static variables), we must instantiate an object from it and access its variable or function.

        
    answered by 28.01.2017 / 02:45
    source
    5

    First it is necessary to specify that the Java language specification it is quite accurate in the terms you use, 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 found the following:

      

    There are eight types of variables:

         
  • A class variable is a declared field using the reserved word static within a class declaration or with or without the reserved word static within a declaration of an interface. A class variable is created when its class or interface is prepared and is initialized to a default value. The class variable ceases to exist when its class or interface is downloaded.
  •   
  • An instance variable is a declared field within the declaration of a class without using the reserved word static . If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value as a part of each new object created from class T or any class that is a subclass of T The instance bariable ceases to exist when the object of which it is field is no longer referenced, after any necessary completion of the object has been completed
  •   

    Class variables belong to the definition of the class. To define a use the keyword static as a modifier.

    public class Car {
    
        public static int total = 0;
    
        public Car() {
            total++;
        }
    
        public static int getTotal() {
            return this.total;
        }
    }
    

    The variable total is shared by all objects of type Car that are created:

    Car carro1 = new Car(); //total=1
    Car carro2 = new Car(); //total=2, la variable se comparte en todas las referencias
    System.out.println(carro1.total); //Imprime 2
    System.out.println(carro2.total); //Imprime 2
    

    Each time I create an object of type Car I increase in one the variable total (number of created objects), since the variable is shared by all the objects (because it belongs to the definition of the class), qua In principle one could think of a class variable as a 'global variable. Since the definition of the variable belongs to the class, it is possible to access it without needing to use a reference to an object, so this is absolutely valid:

    System.out.println(Car.total); 
    

    We access the variable through the name of the class and not some reference to an object.

    Instance variables are those that are declared in a class but without the reserved word static

    public class Book {
    
        private int total = 0;
    
        public Book() {
            total++;
        }
    
        public int getTotal() {
            return this.total;
        }
    
        public void setTotal(int total) {
            this.total = total;
        }
    
    }
    

    Unlike class variables, ownership and responsibility belong to each object that is created. For example:

    Book libro1 = new Book(); //la variable total de esta referencia es 1
    Book libro2 = new Book(); //la variable total de esta referencia es 1 y NO es la misma que la variable total de la referencia libro1
    

    In other words, instance variables are the responsibility of each instance of a class, so each one has its own copy of the variable and modify the value of an instance variable in the object libro1 will not modify the value of the same instance variable with the same name in the object libro2

    libro1.setTotal(10); //Al modificar la variable de instancia total en la referencia libro1 sólo modifico la copia de esta
    System.out.println(libro1.getTotal() == libro2.getTotal()) //Imprime false, ya que son variables diferentes.
    libro2.setTotal(8); //De igual modo, al modificar la variable de instancia total en la referencia libro2 tampoco modifico la variable del mismo nombre en la referencia libro1 porque son variables diferentes.
    System.out.println(libro1.getTotal() == libro2.getTotal()) //Imprime false, ya que son variables diferentes.
    
        
    answered by 28.01.2017 в 04:22