Java Construction methods
A class has a special member method called a constructor method that is used to create an object and initialize the member variable. When you create an object, the constructor method of the class is called automatically.
Construction method Definition rule: The constructor method in Java must have the same name as the class, and there is no return type for the method (including No void). In addition, the constructor method is generally used to describe the public type, so that an instance of the class-object can be created anywhere in the program.
Example: Here is a constructor for the Rectangle class with two parameters representing the length and width of the rectangle:
1 Public class Rectangle {2 Public Rectangle (intint h) {3 width = W; 4 Height = h; 5 }6public Rectangle () {}7 }
Each class has at least one construction method. If you do not write a constructor, the Java programming language will provide a default, the constructor method has no parameters, and the method body is empty. If a construction method is already defined in a class, the default construction method is no longer provided by the system.
Java destructor method
When the garbage collector is about to release memory for a useless object, the object's Finalize () method is called first. If the garbage collector does not always perform a garbage collection operation before the program terminates, the garbage collector will never call the Finalize () method of the useless object. The protected type's Finalize () method is provided in the object base class of Java, so any Java class can override the Finalize () method, typically in the destructor method, to dispose of the related resources occupied by the object.
The garbage collection operation of a Java virtual machine is completely transparent to the program, so the program cannot anticipate when a finalize () method of a useless object is called. If a program consumes only a small amount of memory and does not cause serious memory requirements, the garbage collector may not release the memory occupied by those useless objects, so the Finalize () method of these objects has not been invoked and the program terminates.
Even if the program explicitly calls the System.GC () or Runtime.gc () method, there is no guarantee that the garbage collection operation must be performed, nor does it guarantee that the object's finalize () method must be called.
When the garbage collector executes the Finalize () method, if an exception occurs, the garbage collector does not report an exception and the program continues to function correctly.
@Override protected void Finalize () { System.out.println ("in Finalize");}
In Java programming, we generally do not need to write the destructor method, here just to understand it.
Java constructor method and destructor method instance anatomy