The examples in this article describe the usage of the static keyword in Java and are shared with you for your reference. The specific analysis is as follows:
1. Introduction:
1. In a class, the member variable declared with static is a static member variable. It is a public variable of the class and is initialized when it is used for the first time. For all objects of the class, there is only one copy of the static member variable.
2. The method declared with static is a static method. When the method is called, the reference of the object will not be passed to it, so non-static members cannot be accessed in the static method. (Static methods are no longer called for an object, so non-static members cannot be accessed)
3. Static members can be accessed through object reference or class name (no instantiation required).
Note: Static variables are mostly used for counting functions. (Singleton mode and the like are often used)
2. Program code:
public class TestStatic{ private static int sid; private String name; int id; public TestStatic(String name){ this.name = name; id = sid ++; } private void info(){ System.out.println("My name is: "+name+",Id is: "+id+"."); } public static void main(String args[]){ TestStatic.sid = 100; TestStatic s1 = new TestStatic("lili"); TestStatic s2 = new TestStatic("tom"); s1.info(); s2.info(); }}
The running results are shown in the figure below:
I hope this article will be helpful to everyone’s Java programming.