[Java] object oriented: static static attribute / method / code block

Static modifies the properties or methods of a class

  • Instance property is the independent memory space (multiple copies) held by each object. If the object is modified unilaterally, other objects will not be affected.
  • Static attribute, the instance attribute decorated by static, is. Static property is a shared space held by the whole class. Any object modification will affect other objects.

Java: cannot declare the local variable in the method body as static!

Static properties: class properties
Static methods: class methods
You do not need to create an object. You can directly access [recommended] by class name: class name. Static member

public class TestStaticField {
      public static void main(String[] args) {
            MyClass mc1 = new MyClass();
            mc1.a = 10;
            //mc1.b = 100;
            MyClass.b = 100;
            
            MyClass mc2 = new MyClass();
            mc2.a = 20;
            //mc2.b = 200;
            MyClass.b = 200;
            System.out.println(mc1.a + " " + mc2.a);
            System.out.println(MyClass.b + " " + MyClass.b);
            System.out.println();
            mc1.method2();
            System.out.println();
            mc2.method2();
      }
}
/**
* Class information: class name com.day16.t1 ﹣ static.myclass
* Who is the parent class: java.lang.Object
* Instance property: int a = 0
* Static attribute: int b = 0; double PI = 3.14;
* Example method: xxx
* Static method: xxx
* Class creation time: XX XX XX XX XX: XX: XX
* Compiled JDK version of class: JDK 8.xx.xx (major version number. Minor version number)
* Class: MD5 checksum
*/
class MyClass {
      int a; // Instance attribute
      static int b; // Static attribute
      static double PI = 3.14; // Static attribute (initial value assigned)
      public static void method1() {
            System.out.println("method1()...");
      }
      
      public void method2() {
            //System.out.println(MyClass.a);
            System.out.println(MyClass.b);
            System.out.println(MyClass.PI);
            MyClass.method1();
      }
}
/* Output:
10 20
200 200
200
3.14
method1()...
200
3.14
method1()...
*/
// Count the number of times a class is created
public class TestApplyStaticField {
    public static void main(String[] args) {
        Student[] stus = new Student[10];
        
        for (int i = 0; i < stus.length; i++) {
            stus[i] = new Student();
        }
        
        System.out.println("count Final value:" + Student.getCount()); //10
    }
}


class Student {
    private static int count = 0;
    
    public Student() {
        count++;
    }
    
    public static int getCount() {
        return count;
    }
}

For example, these common static methods are directly called by class name
Arrays.copyOf();
Arrays.sort();
Math.random();
Math.sqrt();

  • Static method rules:
  1. Static methods allow direct access to static members (this is not required);
  2. Static methods do not allow direct access to non static members;
  3. this or super keywords are not allowed in static methods;
  4. Static methods can be inherited, cannot be rewritten (overwritten), and have no polymorphism;
  • static skills
    When executing a class, you can use static to define a static code area for the initialization action you want to execute first. When the class is loaded, it will be executed only once.
    Syntax:
public class example {
    // Static code block: mainly used for initialization before class execution
    static {
        // do some init things.
    }
}

Class loading

When the JVM uses a class for the first time, it needs to find the. Class file of the class through CLASSPATH
Load the description information of the class in the. Class file into memory and save it
For example: package name, class name, parent class, property, method, construction method
That is, for a class, the loading operation is only done once.

  • Loading time:
  1. create object
  2. Create a subclass object
  3. Accessing static properties
  4. Call static method
  • Call class loading syntax
Class.forName("Fully qualified name");
  • Class loading:
    Trigger: execution of static attributes and static code blocks - (1 time only)
    Order: executing static code blocks after static attribute initialization
    Function: it can be called static property assignment or necessary initialization behavior
public class TestClassLoad {
      public static void main(String[] args) throws Exception {
            //new Super();
            //Super.method();
            //System.out.println("------------------------------------");
            //Super.method();
            //System.out.println("------------------------------------");
            //Class.forName("com.day16.t3_classloaded.Super"); / / static attribute, static code block (execute first and only once)
            
            Class.forName("com.day16.t3_classloaded.Sub");
            System.out.println("------------------------");
            new Sub();
            System.out.println("************************");
            new Sub();
      }
}
//Calling sequence: ↓↓
class Super {
   // 1.1 static attribute (class level: only execute once when loading class, classify all, not object owned)
   static String field2 = "Parent static properties";
   
   // 1.2 static code block (class level: only execute once when loading class, classify all, not object owned)
   static {
         System.out.println(field2);
         System.out.println("Parent static code block");
   }
   // ----------------------Parent class execution order divider--------------------------
   // 3. Instance properties (executed when creating objects)
   String field1 = "Parent instance properties";
   // 4. Dynamic code block (executed when creating objects)
   {
         System.out.println(field1);
         System.out.println("Parent dynamic code block");
   }
   
   // 5. Nonparametric construction method (executed when the object is created)
   public Super() {
         super();
         System.out.println("Construction method of parent class without parameters");
   }
   // 6. Static methods in the class (can be called directly by the class name and executed multiple times)
   public static void method() {
         System.out.println("Static methods in parent class");
   }
}

class Sub extends Super {
   // 2.1 static attribute (class level: only execute once when loading class, classify all, not object owned)
   static String subfield2 = "Subclass static properties";
   // 2.2 static code block (class level: only execute once when loading class, classify all, not object owned)
   static {
         System.out.println(subfield2);
         System.out.println("Subclass static code block");
   }
   // 7. Instance properties (executed when creating objects)
   String subfield1 = "Subclass instance properties";
   // 8. Dynamic code block (executed when creating objects)
   {
         System.out.println(subfield1);
         System.out.println("Subclass dynamic code block");
   }
   // 9. Nonparametric construction method (executed when the object is created)
   public Sub() {
         super();
         System.out.println("Subclass nonparametric construction method");
   }
   // 10. Static methods in the class (can be called directly by the class name, and can be executed multiple times)
   public static void submethod() {
         System.out.println("Static methods in subclasses");
   }
}
/* Output:
Parent static properties
 Parent static code block
 Subclass static properties
 Subclass static code block
------------------------
Parent instance properties
 Parent dynamic code block
 Construction method of parent class without parameters
 Subclass instance properties
 Subclass dynamic code block
 Subclass nonparametric construction method
************************
Parent instance properties
 Parent dynamic code block
 Construction method of parent class without parameters
 Subclass instance properties
 Subclass dynamic code block
 Subclass nonparametric construction method
*/

Static static attributes / methods / code blocks are summarized as follows:
(1) Features:
1. Static is a modifier. The member variable modified by static is called static variable or class variable.
2. static decorated members are shared by all objects.
3. Static takes precedence over objects because the members of static already exist as the class loads.
4. There is more than one way to call static decorated members, which can be called directly by the class name (class name. Static member).
5. The data decorated by static is shared data, and the data stored in the object is unique data.
(2) Difference between member variable and static variable:
1. Life cycle differences:
Member variables exist as objects are created and are released as objects are recycled.
Static variables exist with the class loading and disappear with the class disappearing.
2. Different ways of calling:
Member variables can only be called by objects.
Static variables can be called by objects or by class names. (class name is recommended)
3. Aliases are different:
Member variables are also called instance variables.
Static variables are called class variables.
4. Different data storage locations:
Member variable data is stored in the object in heap memory, so it is also called object specific data.
Static variable data is stored in the static area of method area (shared data area), so it is also called shared data of objects.
(3) Precautions for static use:
1. Static methods can only access static members (non static can access both static and non static).
2. this or super keywords cannot be used in static methods.
3. The main function is static.

234 original articles published, 240 praised, 600000 visitors+
His message board follow

Keywords: Attribute Java JDK jvm

Added by fxchain on Mon, 24 Feb 2020 13:58:35 +0200