5. Initialization and Cleaning
5.1 Use constructors to ensure initialization
-
Naming Specification: Use the same name as the class
- Reason resolution: First, the name may conflict with the member name in the class; second, calling the constructor is a compiler task, which requires the compiler to identify clearly.
- Note: Since the constructor name needs to be the same as the class name, the rule of "lowercase for each method" does not apply to the constructor
-
classification
- Default constructor (parametric constructor)
- Parametric constructor
-
Notes
- Only when an object is created, storage space is allocated to the object and the corresponding constructor is invoked.
- A parametric constructor is a special type of method that has no return value, unlike a return value of void; a void type method can modify the return type, such as changing void to int, but the constructor cannot modify it.
5.2 Method overload
-
Constructor Overload
-
rule
- Same name
- Different parameters, types or quantities
-
For example, trees are classified as saplings and centenarians, and centenarians are constructed with parameters of tree height, while saplings are constructed without parameters, because there are generally no high attributes - >
5.2.1 Method of Distinguishing Heavy Load
- Method: Each overloaded method has a unique list of parameter types
-
Notes
- The same parameters but different orders can be distinguished, but the readability is poor.
5.2.2 Basic types of overloading
-
rule
-
Narrow conversion if the parameter type passed in is greater than the type declared by the overloaded method
public class TestOverride { void f1(int f){ System.out.println(getType(f)); System.out.println(f); } public static String getType(Object object){ String typeName=object.getClass().getName(); int length= typeName.lastIndexOf("."); String type =typeName.substring(length+1); return type; } public static void main(String[] args) { TestOverride testOverride = new TestOverride(); testOverride.f1(100); // Narrowing Conversion testOverride.f1((int) 3000.08); } }/* output Integer 100 Integer 3000 */
-
If the parameter type passed in is less than the type declared by the overloaded method, the data type is promoted
public class TestOverride { void f1(double f){ System.out.println(getType(f)); System.out.println(f); } public static String getType(Object object){ String typeName=object.getClass().getName(); int length= typeName.lastIndexOf("."); String type =typeName.substring(length+1); return type; } public static void main(String[] args) { TestOverride testOverride = new TestOverride(); testOverride.f1(100); testOverride.f1(3000.08); } }/* output Double 100.0 Double 3000.08 */
-
5.2.3 Distinguishing overload methods by return values
Unable to use, because if you do not get the return value, it is indistinguishable to use only the f() method.
5.3 Default Constructor
-
rule
- If there is no constructor in the class, the compiler will automatically create the default constructor, which is a parametric constructor.
- If a constructor has been defined in a class, the compiler will not create <! -- for example, if only a parametric construct is defined, then an error will be reported if a parametric construct is used - >.
5.4 This keyword
-
purpose
- Represents a reference to the object that calls the method, which is the reference to the object of the current class.
- Ability to pass the current object to other methods
-
rule
- Can only be used within a method
- If a method in a class is called within a method, the this keyword is not required
5.4.1 Call the constructor in the constructor
-
rule
- Ability to call constructors in constructors
- Two cannot be invoked
- Constructor calls need to be placed at the very beginning
-
Test
class TestThis { String s = "initial value"; int i; // Parametric constructor TestThis(String s,int i){ System.out.println("Build s and i"); } // The parametric constructor uses this call TestThis(){ this("This",32); } public static void main(String[] args) { TestThis testThis = new TestThis(); } }
5.4.2 static Meaning
- purpose
The static method is invoked by the class itself without creating the object.
-
rule
- this method cannot be used in static because non-static methods cannot be invoked in Static methods
5.5 Cleaning up: Ending Treatment and Garbage Recycling
-
Principle of Finalize
- When the garbage collector is ready to release the storage space occupied by the object, the finalize method is called first.
- When garbage collection occurs, the memory occupied by the object is actually reclaimed
-
Notes
- Objects may not be garbage collected
- Garbage collection is not the same as destructing <!--functions that must be used to destroy objects in C++-->
-
Recycling process
- Reachable state: reachable state after object creation
- Restorable state: When a reference is lost, it is restorable. In this state, the garbage collector calls the finalize method. If a reference is retrieved, it becomes reachable.
- Unreachable state: When the reference is completely lost, and the finalize method has been executed without reachable state, the reference is permanently lost
5.5.1 Usage of finalize
Garbage collection is only related to memory. When the java virtual machine does not run out of memory, it will not waste memory to perform garbage collection.
Finalize is not a reasonable way to clean up, finalize calls are uncertain and may have been recycled before execution.
In JDK9, finalize has been marked as obsolete
Working Principle of 5.5.4 Garbage Recycler
1. Reference Count Recovery
- Principle: Store the number of references in the object header, and when the number of references is zero, release the space.
- Advantage
- Real-time, no need to wait for post-processing of insufficient memory, zero reference is released
-
shortcoming
-
Memory cannot always be freed when circular references occur
<! - AB objects are null, but garbage collection cannot be achieved due to circular references - >.
Class TestA{ public TestB b; } Class TestB{ public TestA a; } public static void main(String[] args){ TestA a = new TestA(); TestB b = new TestB(); a.b = b; b.a = a; a = null; b = null; }
-
2. Adaptive garbage collection
- Technological process
Stop-copy-mark-sweep
-
shortcoming
- Need to occupy content, copy objects
5.6 member initialization
-
rule
- Basic types of data, with initial values
- Object references in classes with an initial value of null
5.6.1 Specified initialization
-
Method
- Direct Assignment of Basic Types
- New class object
- Initial values are provided by calling methods
5.7 Constructor Initialization
Automatic initialization occurs before the constructor is invoked, i is set to zero, and then assigns a value of 7.
Class Counter{ int i; Counter(){ i = 7; } }
5.7.2 Object Creation Process
- Constructors are static methods of classes that locate. class files when creating objects
- Load the. class file and the static type action will be executed
- When creating objects with new, first allocate storage space on the heap
- All basic types in the object are set to default values and referenced to null
- Perform all initialization actions that appear at the field definition
- Execution Constructor
5.7.3 Explicit static initialization
-
Static initialization time
- First generation of objects of this class
- First access to static data members of this class
public class Car { // Two static string fields, one initialized at the definition and the other in the static block static String string1 = "defInBegin"; static String string2; static { string2 = "defInStatic"; print("Explicit static initialization"); } static void printMed(){ print(string1); print(string2); } Car(){ print("Car()"); } public static void main(String[] args) { // First generation of objects new Car(); } }/* output Explicit static initialization Car() */
5.7.4 Non-static instance initialization
-
Differentiation from static initialization
- Static initialization is performed only once, and non-static instance initialization can be performed many times
- Static initialization executes earlier than non-static instance initialization, before the construction method
5.8 Array Initialization
- Definition: A sequence of objects of the same type encapsulated in an identifier name or a sequence of primitive types of data
-
Usage method
// Definition int[] i; // Fixed members i.length; // Array size // Initialization Definition int[] a = new int[10]; // Decided by random numbers Random rand = new Random(57); int[] b = new int[rand.nextInt(20)]; // Initialization // Method 1 a[i] = rand.nextInt(20); // Method 2 Integer[] a = { new Integer(1), new Integer(2), 3, }; // Method 3 Integer[] b = new Integer[]{ new Integer(1), new Integer(2), 3, }
-
Be careful
Objects that create classes refer to arrays and do not invoke class constructors, because only arrays are instantiated, and no classes are instantiated.
public class Book { Book(String s){ print("Initial"); print(s); } public static void main(String[] args) { Book[] books = new Book[10]; } }/* output Empty, because no class is instantiated, just an array is instantiated */
5.8.1 Variable parameter list
-
Method
- Method 1: Create a method with Object arrays as parameters, which can be applied to situations where the number or type of parameters are unknown.
- Method 2: Use three points to create a variable parameter list, which can be applied to a list of known types and unknown quantities.
-
Realization
public class TestObjectArray { static void printArray(Object[] args){ for (Object s : args){ System.out.println(s); } } // Method 2 static void f(int... args){ System.out.println(args.length); } public static void main(String[] args) { // Method 1 printArray(new Object[]{ new Integer(35),new Double(23.34),new String("dsaf") }); f(2,4,6,4); } }/* output 35 23.34 dsaf 4 */
5.9 Enumeration Types
- enum keyword: declares a set of integer constants <! -- seven days a week can be defined as an enumeration type - >.
-
Usage method
public enum MoneyValue{ ONE, FIVE, TEN, TWENTY, FIFTY, HUNDRED; }
- An enumeration type called MoneyValue with six named values, all constants
- Output the order of declarations through the. ordinal() method
- Returns all members of the enumeration type as arrays through the. value() method
-
enum and switch are used together
package TwentyTwo; public class Money { public enum MoneyValue{ ONE, FIVE, TEN, TWENTY, FIFTY, HUNDRED; } public static void main(String[] args) { for (MoneyValue mv: MoneyValue.values() ) { switch (mv){ case ONE: System.out.println("This is smallest"); System.out.println(mv.ordinal()); break; case FIVE: System.out.println("This is second"); break; case TEN: System.out.println("This is third"); break; case TWENTY: System.out.println("This is forth"); break; case FIFTY: System.out.println("This is fifth"); break; case HUNDRED: System.out.println("This is largest"); break; } } } }
-
The difference between enumeration and array
- An array is a collection of multiple data items of the same type; enumeration is a new type, allowing constant representation of specific data fragments.
-
Before adding enumeration, the way to create constant aggregation is simpler and safer; after adding enumeration, the way to create constant aggregation is simpler and safer.
public class Test { public static final int A = 1; public static final int B = 2; public static final int C = 3; public static final int D = 4; public static final int E = 5; }
public class Test { public enum Grade{ A,B,C,D,E; }; }