The difference between member variables, instance variables, and class variables in JAVA

java three variable types

  • Class variables: also known as global static variables independent of the method function, there is static
  • Instance variable: independent of the method function, without static modification, also called global variable
  • Member variables: defined in the method function, also called local variables

Class variable

Global static variables, there is only one in the entire program, no matter how many objects are created, for example

 public class 	Person(){
    
    
 public static int i=0;
}
public  static void main(String[] args){
    
    
		Person person=new Person();
		person.i++;
		Person person1=new Person();
		person1.i++;
	}

Here, the i obtained by person is 1; while the i obtained by person1 is 2;

Instance variable

According to the object creation, there is a definition initialization, and the object is destroyed as the object is destroyed. Create different objects whose values ​​are bound to their respective objects. An object carries its own instance object, and an object has an instance variable.

public class TestTwo {
    
    
	
	public List<String> list=new ArrayList<String>();
}
@Test
	public  void sdsd(){
    
    	
		TestTwo one=new TestTwo();
		one.list.add("string");
		TestTwo one1=new TestTwo();
		one1.list.add("string2");		
       System.out.println( one.list);					
	}

Here one object outputs string, one1 outputs string2. Because the objects of one and one2 are different objects

Member variables

Defined in the method function, it is generated when the function is called, and destroyed when the function is ended, regardless of the number of objects.

public class TestTwo {
    
    
	
	public void getNumber(){
    
    
	int i=0;
	i++;
	System.out.println(i);
}
@Test
	public  void sdsd(){
    
    	
		TestTwo one=new TestTwo();
		one.getNumber();
		TestTwo one1=new TestTwo();
		one1.getNumber();				
	}
这里输出的都是1.

Reference link: https://blog.csdn.net/dingwang9210/article/details/101385683 .

Guess you like

Origin blog.csdn.net/weixin_40620651/article/details/114995896
Recommended