classperson{PrivateString name; Private intAge ; /** Assuming the nationality of each person object is the same, it would be unreasonable to assign a value to each call. * With static modification, nationality is first established, and each object is created by default, which is given the nationality. */ StaticString country = "China"; Person (String name,intAge ) { This. Name =name; This. Age =Age ; } Public voidsetName (String name) { This. Name =name; } PublicString GetName () {returnname; } Public voidSetage (intAge ) { This. Age =Age ; } Public intGetaage () {returnAge ; } Public voidShow () {SYSTEM.OUT.PRINTLN (name+ "," +Age ); } /** Therefore, instead of requiring an object to call the method, use the static modifier, called directly with the class Person.sleep. * Therefore: * The function does not have access to properties in the object, it is decorated with static. */ Public Static voidsleep () {System.out.println (Whirring); }}classStaticdemo { Public Static voidMain (string[] args) {/** If the Create object calls the Sleep method, but the sleep method does not have access to the object's properties, then the object's build is meaningless. */ //Person p = new Person ("AAA", +);Person.sleep (); System.out.println (Person.country); }}
Static keyword static is a member modifier.
Characteristics
Members that are modified by static can be called directly by the class name;
Static members take precedence over the existence of objects;
Static members are loaded as the class loads and disappear as the class disappears. The static member life cycle is very long.
Precautions
Static methods can access static members only, cannot access non-static members, and non-static methods have access to static methods and member variables.
The This and super keywords cannot be in a static method. (Reason is that static methods are built earlier than objects)
The main function is static.
The difference between a static variable and a member variable
The difference in name
A member variable is also called an instance variable, and a static variable is also called a class variable.
Differences in memory storage
Member variables are stored in the heap memory object, and static variables are stored in the static area of the method area.
Different life cycle
The member variable appears as the object appears and disappears as the object disappears.
Static variables appear as the class appears, disappearing as the class disappears.
Use of the static modifier static for Java