A brief analysis of the difference between Java variables

  • 2020-04-01 02:36:00
  • OfStack

Class variables are also called static variables, that is, the variable before the static variable;
Instance variables are also called object variables, that is, variables without static;
The difference between the two is:
Class variables (static variables) are all objects in common, one of the objects to change its value, other objects are the result of the change, and the class variables can be directly through the class name to call such as: a.xings;
An instance variable is private to an object, and an object changes its value without affecting other objects. As the name implies, an instance variable belongs to an instance, so it can only be invoked through an instance, such as: A A =new A(); A.n ame.
A bad example: a class variable is like a person's last name. An instance variable is like a person's first name.
Ex. :

public class A{  
static  int xingS = 0; //Class variables    
private int name = 0; //Instance variable & NBSP;  
String id; //Instance variable & NBSP;
private String colorType; //Instance variable & NBSP;  
private int size; //Instance variable & NBSP;  
private static String depart; //Class variables    f
inal String name="zwm"; //constant
} 
public class B{   
public void main (String[] args){       
A son1= new A();       
A son2= new A();       
son1.xingS = 3;  //Is equivalent to
A.xingS = 3;       
son1.name = 4 ;       
System.out.println(son2.xingS); //The results of 3            
//Class variables are for all objects, so son1 changes xingS, and son2's a changes & NBSP;          
System.out.println(son2.name); //The results of 0            
//The instance only changes itself, so the name of the son1 object changes, without affecting the name of the son2 variable & NBSP;
}
}

Class variables, also known as static member variables, can already exist in memory without creating an object, and when an instance object is created,
In memory, a segment of memory is allocated for each non-static member variable of each instance object to store the values of all non-static member variables of that object.
Even though two different instance objects belong to the same class, their non-static member variables of the same name occupy different Spaces in memory.
Static member variables are the same as class variables. All instance objects share a class variable, and there is only one place in memory for the value of the class variable.
Therefore, if an object changes the value of a class variable, another object changes the value of a class variable.

Related articles: