Java uses static to modify member variables

static (static \ modifier)

1. Static modification of member variables: If there is data that needs to be shared with all objects, then static modification can be used .

How to access static member variables:

Method 1: You can use the object to access.
Format: object.variablename.

Method 2: You can use the class name to access.
Format: classname.variablename;

Notice: 
1. Non-static member variables can only be accessed using the object, not the class name.
2. Never use static to modify member variables for the convenience of accessing data. Only the data of member variables is really needed to be shared.
Only use static modification.

Application scenarios of static modification member variables: If a data needs to be shared by all objects, static modification can be used at this time.

class Student{

	String name;
	
	//使用了static修饰country,那么这时候country就是一个共享的数据。

	static	String  country  = "中国";	//国籍
	
	//构造函数
	public Student(String name){
		this.name = name;
	}
}

class Demo9 {

	public static void main(String[] args) 
	{
		Student s1 = new Student("张三");
		Student s2 = new Student("陈七");

		s1.country = "小日本";
		System.out.println("姓名:"+s1.name+" 国籍:"+ s1.country); //  小日本
		System.out.println("姓名:"+s2.name+" 国籍:"+ s2.country); // 小日本
	}
}

If the static String country in the code removes the static modification, then the final s1.country=" Little Japan ", s2.country=" China "



/*
需求: 统计一个类被使用了多少次创建对象,该类对外显示被创建的次数。
*/
class Emp{
	
	//非静态的成员变量。
	static	int count = 0;	//计数器

	String name;
	
	//构造代码块
	{
		count++;
	}

	public Emp(String name){
		this.name = name;

	}

	public Emp(){  //每创建一个对象的时候都会执行这里 的代码
		
	}
	
	public void showCount(){
		System.out.println("创建了"+ count+"个对象");
	}
}

class Demo11 
{
	public static void main(String[] args) 
	{
		Emp e1 = new Emp();
		Emp e2 = new Emp();
		Emp e3 =new Emp();
		e3.showCount();
	}
}

The difference between static member variables and non-static member variables:
1. The difference in function:
1. The role of static member variables share a data for all objects to use.
2. The role of non-static member variables is to describe the public properties of a class of things.
2. Differences in quantity and storage location:
1. Static member variables are stored in the memory of the method area, and only one piece of data exists.
2. Non-static member variables are stored in heap memory, and there are n pieces of data for n objects.
3. Differences in life cycle:
1. Static member variable data exists with the loading of the class and disappears with the disappearance of the class file.
2. Non-static member data exists as the object is created and disappears as the object is reclaimed by the garbage collector.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324106011&siteId=291194637