Initializing and cleaning
Initialization and cleanup are two issues that involve security. A large part of the error in the previous program originated from improper initialization and cleanup. In Java, there is a series of initialization mechanism to ensure the reasonable initialization of data objects, and the garbage collector mechanism is used to ensure the recovery of object memory. 1. Initialization mechanism in Java
In Java class definitions, which mainly involve class attributes (that is, static fields), object properties, and local variables in the method, there are two main ways to initialize them: provide an initial value when the variable is defined; (base data type is initialized to False or 0, object type is initialized to null) Do not provide an initial value when the variable is defined, and force it to initialize when it is defined (otherwise a compile-time error occurs);
The advantage of the first approach is that providing an initial value makes programming more flexible, but the disadvantage is that if you forget to initialize it correctly, using the default initial value of the variable causes errors and is not easy to detect. The advantage of the second approach is that it is forced to initialize correctly, with the disadvantage of initializing the variable definition, lacking flexibility, initializing the definition, and then changing the later variable when it is used, which causes the cost of two initialization. In Java, class attributes and object properties take the first approach, in particular, object properties, when the different objects are instantiated, variable values need different values, the first way to introduce the constructor in the constructor to initialize the object properties, increase the flexibility of programming (instantiate different objects, their object properties are different, Represents different states of different objects, while avoiding the overhead of two initialization in the second way (the initialization cost of providing an initial value for a variable is less). and the local variable in the method takes the second way, a local variable is used and initialized when the method is invoked, does not represent the state of the object, so there is no need for diversity to satisfy the logic of the method, so the second way can also avoid errors caused by incorrect initialization. overload of the method
Method overloading means that the method names are the same and the argument lists are different, they represent the same class of business logic, but the objects may be different. Why the overload of the method is introduced because in the program language, a name (variable or method) represents a memory address or the entry address of a function, is a code of memory operation, because memory address is not easy to remember and recognize, so use a name substitution with a certain meaning, and in the programming process often appear similar class of logic , the logic is roughly the same and the object is different, need to define different methods, in order to distinguish the need for a longer method name caused a certain coding burden, so introduce method overload mechanism, using the same method name, parameter list can distinguish different functions, as for the internal method signature is the use of method name plus parameter list, And there is no need to consider reducing the burden in the programming process.
The introduction of method overloading also poses some problems, is to pass in the parameter in the method call, the system needs to choose the correct method according to the parameter type resolution, if the parameter type corresponds with type one by one in the parameter list of the method, the selection is also easy, but if the type conversion is required, there will be some problem , and when the system chooses the principle, the parameters of the method call are transformed upwards, and the most recently available method is selected for invocation.
The last thing you need to be aware of is the same type in the parameter list, but the order can also be used as an overload, but you need to avoid this kind of behavior as much as possible. Construction Device
The Java introduction constructor guarantees initialization of object properties. Constructors are used to instantiate different objects of a class, so you can instantiate objects of different states by passing different parameters in the constructor after the default initialization of the object's properties. The constructor can be interpreted as a static method, with no return value, the name of which is the same as the class name, so it must be overloaded when a different constructor is required, which is another reason to introduce the overload (and why the overload of the method is introduced here). The main function of the constructor is the initialization of the object, mainly for object properties.
Class, if there is no constructor defined in the the compiler constructs a default constructor for the class (that is, the parameterless constructor, which does not have any initialization behavior), and if the constructor is defined in the class, the default constructor is no longer constructed (it does not mean that there is no parameterless constructor and can be defined yourself). In the constructor, the logic is to invoke its parent class constructor first (without specifying a call to the parent class parameterless constructor). If the parent class has no parameterless constructor, there is a compile-time error, you can also specify which constructor to invoke the parent class, use super (args), and the sentence is in the first line of the constructor. Otherwise, there will be a compile-time error), and then the logic of initializing the object's properties, defining the diversity of object states through the constructor's argument list.
This is especially true of the invocation problem of the parent class constructor, if the custom class inherits a class, the class does not have a parameterless constructor, the custom class must define the constructor, because the default constructor that is added is a parameterless constructor that does not have any execution logic, so it inherently defaults to calling the parent class's parameterless constructor. The parent class does not have an parameterless constructor and needs to be explicitly invoked, so the custom class must define a constructor, and there is no limit to what the argument list is, but the first line inside the constructor must explicitly call the constructor of one of the parent classes.
In order to simplify programming in the constructor's logical writing process can also invoke the overloaded other constructors, using this (args), the location of this call is not qualified.
Finally, note that the constructor can be understood as a static method of a class, with no return value (that is, void) to instantiate the object, and the instantiated object is not the constructor's return value. Order of initialization
The initialization problem can be divided into two processes, namely the initialization of the class and the initialization of the object. The initialization of a class is the loading of a class instance. is to instantiate the class object in the virtual machine, which performs the initialization of the class attribute, that is, the initialization of the static domain and the static block, in the order that the class of the parent class is initialized, and then the initialization of the static domain or block is performed in the order of Declaration. The initialization trigger condition for a class consists of two one is to use a static or static method of a class (which does not trigger object initialization), and the second is an object instantiation (that is, triggering the initialization of an object); Initialization of an object performs the initialization of an object property, that is, a non-static field in a property. The order is initialized with the object that executes the parent class first, as declared. The default initialization of the object's properties, or the display of the initialization of the declaration, is then performed sequentially (it can be understood that when a subclass instantiates an object, it is necessary to instantiate a parent class as one of its attributes), and finally invoke the constructor.
Therefore, the order of initialization can be summed up as: class initialization of the parent class, class initialization of the subclass, object initialization of the parent class (Initialization of object properties, and then call constructor), object initialization of subclasses (the order is also initialized first property, in call constructor)
Code Sample:
Package initialization; public class Ordertest {//static int a = Child.sfield1;
Execute statement 1 public static void main (string[] args) {System.out.println ("before new Child"); Child child = new Child ();
EXECUTE Statement 2}} class parent{private int parentfield = Getparentfield ();
static int sparentfield = Getsparentfield ();
Static{System.out.println ("Parent static block");
Public parent () {System.out.println ("parent constructor");
private static int Getsparentfield () {System.out.println ("Getsparentfield");
return 0;
private int Getparentfield () {System.out.println ("Getparentfield");
return 0;
} class Child extends parent{private int field1 = GetField1 ();
static int sField1 = GetSField1 ();
static{System.out.println ("static Block");
static int sField2 = GetSField2 (); Public Child () {System.out.println ("childConstructor ");
private int field2 = GetField2 ();
private static int getSField1 () {System.out.println ("getSField1");
return 0;
private static int getSField2 () {System.out.println ("getSField2");
return 0;
private int getField1 () {System.out.println ("getField1");
return 0;
private int getField2 () {System.out.println ("getField2");
return 0;
}
}
The initialization of the class is triggered only when the statement 1 o'clock is executed, and its output is:
Getsparentfield
parent static block
getSField1
static block
getSField2
before new child
When the object is instantiated only when the statement 2 o'clock is executed, the result is:
Before the new child
Getsparentfield the
parent static block GetSField1 the static block
getSField2
Getparentfield
Parent Constructor
getField1
getField2 Child
Constructor
You can see that even the properties declared after the constructor are initialized before the constructor.
Finally, note the initialization of the class, that is, the initialization of the static domain and the static block is performed only once, and the subsequent use of the static domain and the instantiated object will not start the initialization of the class again, only perform subsequent object initialization. 2. End-processing and garbage collection in Java
In Java, objects generated through the new operation are allocated memory in heap space, and Java is responsible for the memory of objects that are no longer used in the Recycle program through the garbage collector. The garbage collector is responsible only for the memory consumed by the discarded objects in the program, while the program is running with some other resources that need to be freed, such as open files, connected networks, and so on. non-available Finalization method Finalize () method
Similar to the destructor in C + +, the Finalize () method is introduced in Java, which works by assuming that once the garbage collector is ready to release the memory space occupied by the object, it first invokes the object's Finalize () method. And frees the memory space occupied by the object when the next garbage collection action occurs. However, this method does not necessarily get invoked, so it is unreasonable to clean out the resources in this method except for memory.
The garbage collection problem in Java has the following characteristics:
-1. Object may not be garbage collected
-2. Garbage collection does not equal the destructor
-3. Garbage collection is only related to memory
The work of the garbage collector in Java triggers the GC when the memory is not in use, when the memory of the object is no longer used, and when an object is no longer used, it is not guaranteed to be recycled, and the Finalize () function is not guaranteed to be invoked.
public class Finalizetest {public
static void Main (string[] args) {
//TODO auto-generated method stub
New Fi Nalizetest ();
System.GC ();
}
@Override
protected void Finalize () throws Throwable {
//TODO auto-generated method Stub
super.finalize ();
System.out.println ("Finalize");
}
If you do not explicitly call SYSETEM.GC (), the Gc,finalize () method is not triggered and will not be invoked. Garbage collection is only about memory, so other resources associated with the object require explicit cleanup in a reasonable way. How the garbage collector works
Java simplifies programming by using the garbage collector to reclaim the memory space occupied by objects that are generated by the new operation and that are no longer used. And garbage collection faces three problems:
-1. When to recycle
-2. What objects are recycled memory
-3. How to Recycle
The
For the first problem is what was previously said to trigger a GC when the Java virtual machine has not enough memory to recycle the memory that is no longer used. And the recycled nature is no longer using the object's memory, how to search for objects that are no longer in use, rather than using reference counting in Java, but using references that are traced back to their surviving stacks or static stores, objects that are no longer referenced are naturally "objects" to be processed, but more complex for recycling algorithms, including "Stop-copy And the mark-sweep algorithm, the former can make the memory after the recovery is relatively neat, easy to allocate memory, but the replication process consumes a lot, and "mark-sweep" is relatively lightweight, but after a while the memory will become fragmented, so Java takes into account the different periods of memory allocation and distribution characteristics of different objects , the use of adaptive, generational, stop-copy, tag-sweep garbage collector, the specific garbage collection process can refer to the relevant books.