Class variable,
A group of children are playing games. From time to time, new people join the game. How many people are playing the game?
Use object-oriented thinking to write programs to solve the following problems:
1 public class ChildDemo {2 public static void main (String [] args) {3 Child Development = new Child (1, "niu"); 4 ch1.joinGame (); 5 Child ch2 = new Child (2, ""); 6 ch2.joinGame (); 7 Child ch3 = new Child (3, ""); 8 ch2.joinGame (); 9 // static variables can be passed through the class name. variable name: 10 System. out. println ("Total =" + child. total); 11} 12} 13 class Child {14 int age; 15 String name; 16 // total is a static variable, without modifiers, any object can access 17 static int total = 0; 18 public Child (int age, String name) {19 this. age = age; 20 this. name = name; 21} 22 public void joinGame () {23 total ++; 24 System. out. println ("adding a child"); 25} 26}
Can be accessed by objects to share resources, thus saving resources. Static variables can also be called class variables.
Class variables:
A class variable is a shared variable for all objects of the class. When an object of the class accesses it, the same value is obtained. When an object of the same class modifies it, the same variable is modified.
Syntax for defining class variables:
Access modifier static data type variable name;
Category variables:
Class Name. Class variable name or object name. Class variable name
See the following code:
Public class Demo {static int I = 1; static {// This static zone block only executes I ++ once; // It is not triggered by the creation of object instances} public Demo () {I ++;} public static void main (String [] args) {Demo dm1 = new Demo (); System. out. println (dm1. I); Demo dm2 = new Demo (); System. out. println (dm2. I );}}
When a class is defined, the static information and information have been written to the code area and automatically executed. Even if no object instance is created, the variables in the static code block are stored in the code area, when an object is instantiated, it has nothing to do with the static code block.
Public class Demo {static int I = 1; static {System. out. println ("execution completed"); // This static region block is only executed once I ++; // It is not triggered by the creation of an object instance} public Demo () {I ++;} public static void main (String [] args) {// Demo dm1 = new Demo (); // System. out. println (dm1. I); // Demo dm2 = new Demo (); // System. out. println (dm2. I );}}
Differences between class variables and instance variables:
Static is called a class variable or a static variable. Otherwise, it is called an instance variable.
Class variables are class-related and public attributes.
Instance variables belong to the attributes of each object individual
Class variables can be directly accessed by class name. Class variable name