[Java] [Java] Differences between instance variables and class variables

1 minute read

Purpose

To understand the difference between instance variables and class variables

Verification environment

  • Eclipse Oxygen.3a Release (4.7.3a)
  • Java8

Source code for verification

** 1. Class variables and instance variables **

qiita.java


public class Oimo {
	public static int CNT_CLASS; //Class variables
	public int CNT_INSTANCE; //Instance variables
}

** 2. Try class variables **

qiita.java


public class Kensho01 {

	public static void main(String[] args) {
		//Class variables
		Oimo oimo3 = new Oimo();
		Oimo oimo4 = new Oimo();

		oimo3.CNT_CLASS = 30;

		System.out.println(oimo4.CNT_CLASS); //30 is output
	}
}

** 3. Try instance variables **

qiita.java


public class Kensho01 {

	public static void main(String[] args) {
		//Instance variables
		Oimo oimo1 = new Oimo();
		Oimo oimo2 = new Oimo();

		oimo1.CNT_INSTANCE = 10;

		System.out.println(oimo2.CNT_INSTANCE); //0 is output
	}
}

Implementation procedure

–Prepare Oimo class with class variables and instance variables. Create two Oimo instances, set the values for the class variables and instance variables of the first instance, and then check the values of the class variables and instance variables set for the second Oimo instance.

Implementation results

–When I set the class variable of the first instance to 30, the class variable of the second instance was also set to 30.
–When I set the instance variable of the first instance to 10, the instance variable of the second instance was set to 0.

Consideration

It turned out that instance variables are variables that are referenced for each instance, and class variables are variables that are commonly referenced by multiple instances. This knowledge is important if you want to write a thread-safe program.

See you again (^_^) Noshi