Java static keywords and Java static variables and static methods
The static modifier can be used with variables and methods to indicate that it is "static".
Static variables and static methods can be accessed through class names, and there is no need to create an object of a class to access the static members of the class, so members modified by static are also called class variables and class methods. Static variables are different from instance variables, and instance variables are always accessed through objects because their values vary between objects.
Please see the following example:
public class Demo { static int i = 10; int j; Demo() { this.j = 20; } public static void main(String[] args) { System.out.println("class variable i=" + Demo. i); Demo obj = new Demo(); System.out.println("Instance variable j=" + obj.j); }}
Running results:
Class variable i=10 Instance variable j=20
static memory allocation
Static variables belong to classes and do not belong to any independent objects, so you can access static variables without creating instances of the class. This result is because the compiler only creates a copy of static variables for the entire class, that is, only allocates one memory space. Although there are multiple instances, these instances share the memory. Instance variables are different. Every time an object is created, memory space will be allocated. The memory of different variables is independent of each other and does not affect each other. Changing the instance variable of object a will not affect object b.
Please see the following code:
public class Demo { static int i; int j; public static void main(String[] args) { Demo obj1 = new Demo(); obj1.i = 10; obj1.j = 20; Demo obj2 = new D emo(); System.out.println("obj1.i=" + obj1.i + ", obj1.j=" + obj1.j); System.out.println("obj2.i=" + obj2.i + ", obj2 .j=" + obj2.j); }}
Running results:
obj1.i=10, obj1.j=20obj2.i=10, obj2.j=0
Note: Although static variables can also be accessed through objects, they are not recommended and the compiler will also generate warnings.
In the above code, i is a static variable. Changing the value of i through obj1 will affect obj2; j is an instance variable. Changing the value of j through obj1 will not affect obj2. This is because obj1.i and obj2.i point to the same memory space, while obj1.j and obj2.j point to different memory spaces. Please see the following picture:
Note: The static variable will be initialized when the class is loaded. That is, as long as the class is loaded, it will be initialized regardless of whether you use this static variable or not.
Summary: Class variables are modified with the keyword static. When the class is loaded, the memory of the class variable is allocated. When the class instance object is generated, this memory (class variable) will be shared, any object to the class. Changes to variables will affect other objects. There are two ways to access externally: access through objects or access through class names.
Static method
A static method is a method that cannot perform operations on an object. For example, the pow() method of the Math class is a static method with a syntax of Math.pow(x, a), which is used to calculate the power of a of x, and there is no need to create any Math objects when used.
Because static methods cannot operate objects, instance variables cannot be accessed in static methods, and can only access static variables of their own class.
The static method can be used in the following situations:
A method does not need to access the object state, and its required parameters are provided by explicit parameters (for example, Math.pow()).
A method only needs to access static variables of the class.
Readers must have noticed that main() is also a static method that does not operate on any objects. In fact, there are no objects at the time of the program startup, the main() method is the entry to the program and will be executed and the objects required by the program are created.
Summary of static variables and static methods:
A static method of a class can only access static variables;
A static method of a class cannot directly call non-static methods;
If access control permission allows, static variables and static methods can also be accessed through objects, but are not recommended;
The current object does not exist in the static method, so this cannot be used, and of course super cannot be used;
Static methods cannot be overwritten by non-static methods;
The constructor does not allow the declaration of static;
Local variables cannot be modified with static.
Examples of static methods:
public class Demo { static int sum(int x, int y){ return x + y; } public static void main(String[] args) { int sum = Demo.sum(10, 10); System.out .println( "10+10=" + sum); }}
Running results:
10+10=20
The static method does not require any instance of the class it belongs to will be called, so there is no value of this and the instance variable cannot be accessed, otherwise it will cause a compilation error.
Note: Instance variables can only be accessed through objects and cannot be accessed through classes.
Static initializer (static block)
A block is a piece of code surrounded by braces. A Static Initializer is a static block that exists in a class and outside a method. Static initializers are only executed once when the class is loaded (when the class is used for the first time) and are often used to initialize static variables.
Sample code:
public class Demo { public static int i; static{ i = 10; System.out.println("Now in static block."); } public void test() { System.out.println("te st method: i=" + i); } public static void main(String[] args) { System.out.println("Demo.i=" + Demo.i); new Demo().test(); }}
The result of the operation is:
Now in static block.Demo.i=10test method: i=10
Static import
Static import is a new feature of Java 5, used to import static variables and static methods of classes.
Generally, we write this in import classes:
import packageName.className; // Import a specific class
or
import packageName.*; // Import all classes in the package
And static import can be written like this:
import static packageName.className.methonName; // Import a specific static method
or
import static packageName.className.*; // Import all static members in the class
After importing, you can directly call the static method with the method name in the current class, and you no longer need to use className.methodName to access it.
For frequently used static variables and static methods, they can be imported statically. The advantage of static import is that it can simplify some operations, such as the output statement System.out.println(); is a static variable of the System class. You can import it through import static java.lang.System.*; and directly next time. Just call out.println().
Please see the following code:
import static java.lang.System.*;import static java.lang.Math.random;public class Demo { public static void main(String[] args) { out.println("produced by random number: " + random( )); }}
Running results:
A random number generated: 0.05800891549018705
Java final keyword: block inheritance and polymorphism <br />In Java, when declaring classes, variables and methods, the keyword final can be used to modify it. The data modified by final has the characteristics of "final state" and means "final". The specific regulations are as follows:
The class modified by final cannot be inherited.
The final modification method cannot be rewritten by subclasses.
The variable modified by final (member variable or local variable) becomes a constant and can only be assigned once.
The member variable modified by final must be assigned at the same time as the declaration. If there is no assignment at the time of declaration, there is only one chance of assignment, and it can only be explicitly assigned in the constructor before it can be used.
The local variable modified by final can only declare that it does not assign, and then be assigned at one time.
final is generally used to modify data that cannot be changed at will to avoid misuse, such as methods to implement mathematical triangle methods, exponentiation operations and other functions, as well as mathematical constant π=3.141593, e =2.71828 et al.
In fact, to ensure final state, the java.lang.Math class that provides the above methods and constants has also been defined as final.
It should be noted that if a variable that references a type (the type of any class) is marked as final, then the variable cannot point to any other object. But the content of the object can be changed, because only the reference itself is final.
If the variable is marked final, the result is to make it a constant. Wanting to change the value of the final variable will cause a compilation error. Here is an example of correctly defining final variables:
public final int MAX_ARRAY_SIZE = 25; // Constant name is generally capitalized
Constants cannot be inherited because they have final modification.
Please see the following code:
public final class Demo{ public static final int TOTAL_NUMBER = 5; public int id; public Demo() { // Illegal, the final variable TOTAL_NUMBER was assigned quadratic value// Because ++TOTAL_ NUMBER is equivalent to TOTAL_NUMBER=TOTAL_NUMBER+1 id = ++TOTAL_NUMBER; } public static void main(String[] args) { final Demo t = new Demo(); final int i = 10; final int j; j = 20; j = 30; // Illegal, final variable Perform secondary assignment}}
Final can also be used to modify classes (before the class keyword) to prevent the class from deriveing subclasses. For example, Java.lang.String is a final class. This is done for security reasons, because it is necessary to ensure that once a string is referenced, it must be a string of the class String, not a string of some other class (the String class may be maliciously inherited and tampered with).
Methods can also be modified by final, and methods modified by final cannot be overwritten; variables can also be modified by final, and variables modified by final are not allowed to change their values after the object is created. Once a class is declared as final, the methods contained in that class will also be declared implicitly as final, but the variable is not.
The method modified by final is static binding and will not produce polymorphism (dynamic binding). The program does not need to retrieve the method table when running, which can improve the code execution efficiency. In Java, methods that are modified by static or private will be implicitly declared as final because dynamic binding has no meaning.
Since dynamic binding consumes resources and is often not necessary, some programmers believe that unless there is sufficient reason to use polymorphism, all methods should be modified with final.
This understanding is a bit extreme, because the instant compiler in the JVM can monitor the operation information of the program in real time and can accurately know the inheritance relationship between classes. If a method is not overwritten and is short, the compiler can optimize it, which is called inlining. For example, an inline call to e.getName() will be replaced with accessing the e.name variable. This is a meaningful improvement, because the branch transfer used by the CPU when processing instructions that call methods will disrupt the policy of the prefetch instruction, so this is considered unpopular. However, if getName() is overwritten in another class, the compiler cannot know what the overwritten code will do, so it cannot be inlined.