Static
Static can be decorated with properties, methods, code blocks, inner classes
Characteristics
- Load as the class loads
- Precedence over the existence of objects
- Decorated members are shared by all objects
- When access permission is allowed, the object can not be created and called directly by the class
Static modified properties, which are stored in memory, are only one member of the entire program.
Public classTest { Public Static void Main(string[] args) {Person p =NewPerson (); Person.setname ("TTF");//class can access static methods directlySystem. out. println (Person.name);//Use class to access static properties directly}}class Person {StaticString name;//static properties, intAge//member properties, which belong to the object's Public Static void SetName(String name) {person.name = name; }}
Use
- If a property in a class is decorated with static, this property can only be accessed directly by the class (not by using private adornments), or by a class method with static adornments
- The instance object of the class cannot access static properties (properties with static adornments), and static methods (methods with static adornments)
p.setName("ttf")//错误,p不能访问静态方法同时也不能访问静态属性。
- Static methods cannot access member variables of a class (properties that do not have static adornments), and static methods are class methods
- Once the static property is initialized, which is initialized only once, the entire class has only one variable
Static code block
- A static code block is a code fragment that uses the static modifier.
- If there is more than one static block of code, proceed in order from top to bottom
- Static code blocks are executed before non-static blocks of code
- Static code block executes only once
- Classes are initialized when they are used.
publicclass Test { publicstaticvoidmain(String[] args) { //Person p = new Person(); System.out.println(Person.name);//ttf }}class Person { static String name; int age; /*静态代码块*/ static { "ttf"; }}
"Java Summary" static, static code block