Java: Object creation and initialization process
1. Data types in Java
There are 3 data types in Java: basic data types (in Java, boolean, byte, short, int, long, char, float, and double are basic data types), reference type and null type. Among them, the reference type includes class type (including array) and interface type.
The following statement declares some variables:
int k ;A a; //a is the object variable name of the A data type. B b1,b2,…,b10000;// Assume that B is an abstract class or interface. String s;
Note: From the perspective of data types and variables, the basic data type variables k, class type variables a and s, abstract class or interface type variable b (10,000), are all variables (identifiers).
2. About handle
To distinguish between variable identifiers of reference types and variable identifiers of basic data type, we specifically use Handle to name variable identifiers of reference types. In the above example, b1 to b10000, a, and s are all Handle. Handle intuitively looks at the handle and handle. We use the commonly used Chinese translation of "handle" in the computer world.
2.1 [In Windows Programming] The meaning of a handle is a unique integer used by WONDOWS to identify objects created or used by an application. WINDOWS uses various handles to identify such as application instances, windows, controls, bitmaps, GDI objects, etc. The WINDOWS handle is a bit like a file handle in C language.
From the definition above, we can see that the handle is an identifier that is used to identify an object or project. It is like our name. Everyone will have one. Different people have different names, but there may also be someone with the same name as you. From the data type, it is just a 16-bit unsigned integer. An application almost always obtains a handle by calling a WINDOWS function, which can then be used by other WINDOWS functions to reference the corresponding object.
If you want to know handles more thoroughly, I can tell you that handles are pointers to pointers. We know that the so-called pointer is a memory address. After the application is started, the objects that make up the program reside in memory. If we simply understand it, it seems that as long as we know the first address of this memory, we can use this address to access the object at any time. But if you really think so, you're very wrong. We know that Windows is a virtual memory-based operating system. In this system environment, Windows memory manager often moves objects back and forth in memory to meet the memory needs of various applications. An object is moved means its address has changed. If the address always changes like this, where should we find the object?
To solve this problem, the Windows operating system frees up some internal storage addresses for each application to specifically register the address changes of each application object in memory, and this address (the location of the storage unit) itself remains unchanged. After moving the object's location in memory, the Windows memory manager tells the object's new address to save it. In this way, we only need to remember this handle address to indirectly know where the object is in memory. This address is assigned by the system when the object is loaded (Load), and is released to the system when the system is unloaded.
Handle address (stable) → record the address of the object in memory──────The address of the object in memory(unstable) → Actual object
2.2 The meaning of handles in Java has a deep understanding of the meaning of handles [in Windows programming]. We can say that Handle is a term that we need very much when learning Java. Its meaning is to distinguish "object itself" from object variables (or strictness: variable identifiers of the data type to which the object belongs).
2.3 Return to the variable declaration in 1:
Now, you should have a clear view of the comments below.
int k, j ;//k stores an integer number. A a; //The address is stored in a. B b1,b2,…,b10000;// b1,…,b10000 stores the address inside. String s; //s stores the address.
3. About reference
What is a "citation"? “the identifier you manipulate is actually a 'reference' to an object”. (Thinking in Java 2e)
The translation is: the identifier you manipulate is actually a "reference" to an object. Or to be more precise, translated into: the identifier you operate is actually a "reference" to an object. Obviously, the reference in the original text is something with a sense of direction.
Go back to Java and refer to the ID number of the object, the ID of the object, or the mobile phone number of the object. Of course, more of the saying is that the reference is the room number where the object lives in memory. Intuitively speaking, the reference to an object is the return value when creating an object! A reference is the return value of a new expression.
new A(); Here is an object, but we don't use a handle to hold (hold, hold, save) the reference. From a microscopic perspective, the new expression completes the task of object initialization (three steps, detailed analysis below), and overall, it returns a reference.
Go back to the variable declaration in 1 again and take a look at the comments below.
A a; //Declare handle a, but is not initialized, so the value inside is null. B b1,b2,…,b10000;// Declare handles b1,…,b10000, but are not initialized, so the value inside is null. String s; //Declare handle s, but is not initialized, so the value inside is null.
4. The relationship between handle and reference
A a;//Declare handle a, the value is nulla=new A();//Initialization of the handle (handle = reference; that is, assign the reference to the handle)
Quote: the value of new A(). References can be simply regarded as the address where the object occupies memory space; through references to objects, they can be conveniently distinguished from other objects, and references are the unique identity of the object.
After the handle is initialized, you can use the handle to remotely control the object.
Of course, this is just to explain the creation and initialization of objects from one aspect. After understanding the relationship between handles and references, the entire process of object initialization is analyzed below. Let’s do the following preparations first, talk about stack and stack.
5. Stack and heap in java
In Java, memory is divided into two types: "stack" and "heap" (Stack and Heap). The basic data type is stored in the "stack", and the object reference type is actually stored in the "heap", and the address value of the reference memory is only retained in the stack.
By the way, let's talk about the "==" and "equals() methods" to help understand the concept of both (Stack and Heap).
When comparing variables with "==" in Java, the system uses the value stored in the variable in the stack as the basis for comparison. The value stored in the basic data type in the stack is its containment value, and the value stored in the reference type in the stack is the address value of the object itself points to. The Object class in the Java.lang package has the public boolean equals (Object obj) method. It compares whether two objects are equal. The equals() method of the object returns true only if the two references being compared point to the same object (the handles are equal). (As for the equals() method of the String class, it overrides the equals() method and is not discussed in this article.)
6. Object creation and initialization process
In java object is an instance of the class. In general, when an instantiation of a class, all members of such a class, including variables and methods, are copied into a new instance of this data type. Analyze the following two codes.
6.1 Vehicle veh1 = new Vehicle();
The above statement does the following:
①The "new Vehicle" on the right uses the Vehicle class as a template to create a Vehicle class object (also referred to as a Vehicle object) in the heap space.
②The end of () means that after the object is created, the constructor of the Vehicle class is called immediately to initialize the newly generated object. There must be a constructor. If not created, Java will add a default constructor.
③The "Vehicle veh1" on the left creates a Vehicle class reference variable.
④ The "=" operator makes the object reference point to the Vehicle object just created. (Recall handles and references)
Divide the above statement into two steps:
Vehicle veh1;veh1 = new Vehicle();
It is clearer to write this way. There are two entities: one is the object reference variable, and the other is the object itself. Entities created in heap space are different from those created in stack space. Although they are entities that do exist, it seems difficult to accurately "catch" it. Let’s study the second sentence carefully and find out what the name of the object you just created? Some people say it is called "Vehicle". No, "Vehicle" is the name of the class (the creation template for the object). A Vehicle class can create countless objects based on this, and these objects cannot be called "Vehicle". The object does not even have a name, so it cannot be accessed directly. We can only access objects indirectly through object references.
6.2 Vehicle veh2;
veh2 = veh1;
Since veh1 and veh2 are just references to objects, what the second line does is just assigning the reference (address) of veh1 to veh2, so that veh1 and veh2 point to the unique Vehicle object at the same time.
6.3 veh2 = new Vehicle();
The reference variable veh2 points to the second object instead.
Deduced from the above statement, we can draw the following conclusion: ① An object reference can point to 0 or 1 object; ② An object can have N references to point to it.
Java: Data type conversion
1. Simple types of Java and their encapsulator classes
1.1 Java simple types and encapsulation classes We know that Java language is a typical object-oriented programming language, but considering the advantages of some basic data types being simple in structure, small memory and fast access speed, Java still provides support for these non-object-oriented simple data types. Of course, when Java provides a large number of other classes, it also provides encapsulated classes corresponding to simple data types. Therefore, Java has different data types such as int and Integer (float and Float, double and Double...).
There are two major categories of data types in Java language: one is a simple type, also known as the main type (Primitive), and the other is a reference type (Reference). A simple type variable stores a specific value, while a reference type variable stores a reference to an object.
Java determines the size of each simple type. These sizes do not change with the changes in the machine structure. This size is invariant, which is one of the reasons why Java programs have strong portability.
The following table lists the simple types, occupancy of binary bits and corresponding encapsulator classes defined in Java.
Simple types in table Java
1.2 Why use encapsulation classes. Take int and Integer as an example. Although they essentially represent a 32-bit integer, they are different data types. In fact, the integers directly used in Java are int (as far as int and Integer are concerned). Only when the data must appear as an object's identity, the integer value must be encapsulated into an object with the encapsulator Intege, the corresponding int.
For example: To add an integer to the Vector in the java.util package, the integer value must be encapsulated in an Integer instance as follows:
Vector v=new Vector();int k=121;v.addElemt(new Integer(k));
In addition, Integer, as the encapsulator class corresponding to int, provides many methods, such as Integer construction methods, Integer conversion methods to other numerical types, etc., which are not available in int type data.
2. Constants in Java
We need to pay attention to the following types of constants.
2.1 When hexadecimal integer constants are expressed in hexadecimal, they must start with 0x or 0X, such as 0xff, 0X9A.
2.2 Octal integer constant octal must start with 0, such as 0123, 034.
2.3 Long-type long-type must end with L, such as 9L, 342L.
2.4 Float constants Since the default type of the decimal constant is double type, f(F) must be added after the float type. Variables with decimals are also of double type by default.
float f;
f=1.3f;//F must be declared.
2.5 Character constants Character constants need to be enclosed in two single quotes (note that string constants are enclosed in two double quotes). Characters in Java account for two bytes.
Some commonly used escape characters.
①/r means accepting keyboard input, which is equivalent to pressing the Enter key;
②/n means a newline;
③/t represents a tab character, which is equivalent to the Table key;
④/b represents the backspace key, which is equivalent to the Back Space key;
⑤/' means single quotes;
⑥/'' means double quotes;
⑦// means a slash/.
3. Conversion between simple data types
There are two ways to convert between simple types of data: automatic conversion and cast conversion, which usually happens when the parameters of the expression or method are passed.
3.1 Automatic conversion Specifically, when a "small" data is calculated together with a "large" data, the system will automatically convert the "small" data into "large" data and then perform the calculation. When calling the method, the actual parameters are "small" and the formal parameter data of the called method is "large" (if there is a match, of course, the matching method will be called directly), the system will automatically convert the "small" data into "big" data, and then call the method. Naturally, for multiple overloaded methods of the same name, it will be converted into the "close" "big" data and called.
These types from "small" to "big" are (byte, short, char)--int-long-float-double. What we are talking about here does not refer to the number of bytes occupied, but to the size of the range representing the value.
Please see the following example:
①The following statements can be directly passed in Java:
byte b;int i=b;long l=b;float f=b;double d=b;
② If the low-level type is char type, it will be converted to the corresponding ASCII code value when converting to a high-level type (integral type), for example
char c='c';int i=c; System.out.println("output:"+i);
Output:
output:99;
③For the three types of byte, short, and char, they are horizontal, so they cannot automatically convert each other. The following cast type conversion can be used.
short i=99 ;char c=(char)i;System.out.println("output:"+c);Output:
output:c;
④If there is a method in object polymorphism:
f(byte x){…};f(short x) {…};f(int x) {…};f(long x) {…};f(float x) {…};f(double x) {…};f(double x) {…}; There is also: char y='A'; So, which method will the statement f(y) call? The answer is: f(int x) {...} method, because its formal reference parameter is "large" and is the "closeest".
And for the method:
f(float x) {…};f(double x) {…}; There is also: long y=123L; then, the method called by the statement f(y) is f(float x) {…}.
3.2 Casting When converting "large" data to "small" data, you can use casting. That is, you must use the following statement format:
int n=(int)3.14159/2;
As you can imagine, this conversion may certainly lead to overflow or a decrease in accuracy.
3.3 Automatically enhance the data type of expression. Regarding the automatic enhancement of the type, pay attention to the following rules.
① All values of byte, short, and char types will be promoted to int type;
②If there is an operand that is long, the calculation result is long;
③If there is an operand that is float type, the calculation result is float type;
④If there is an operand that is double type, the calculation result is double type;
example,
byte b; b=3; b=(byte)(b*3);//Byte must be declared.
3.4 Transition type conversion for packaging class Generally speaking, we first declare a variable and then generate a corresponding packaging class, and we can use various methods of the packaging class to perform type conversion. For example:
① When you want to convert float to double type:
float f1=100.00f; Float F1=new Float(f1); double d1=F1.doubleValue();//F1.doubleValue() is the method of returning double value type of the Float class
②When you want to convert the double type to an int type:
double d1=100.00;Double D1=new Double(d1);int i1=D1.intValue();
Convert variables of simple types to the corresponding wrapper class, and the constructor of the wrapper class can be used. That is: Boolean(boolean value), Character(char value), Integer(int value), Long(long value), Float(float value), Double(double value)
In each packaging class, there is always a method of ××Value() to obtain its corresponding simple type data. Using this method, conversion between different numerical variables can also be realized. For example, for a double-precision real-type class, intValue() can obtain its corresponding integer variable, and doubleValue() can obtain its corresponding double-precision real-type variable.
4. Conversion between strings and other types
4.1 Conversion of other types to strings ① Call the string conversion method of the class: X.toString();
②Automatic conversion: X+";
③ Methods using String: String.volueOf(X);
4.2 Convert the string to other types as values ① First convert it to the corresponding wrapper instance, and then call the corresponding method to convert it to other types. For example, the format of converting the double type value of the "32.1" in the character is: new Float("32.1").doubleValue(). You can also use: Double.valueOf("32.1").doubleValue()
② Static parseXXX method
String s = "1";byte b = Byte.parseByte(s );short t = Short.parseShort(s );int i = Integer.parseInt(s ); long l = Long.parseLong(s );Float f = Float.parseFloat(s );Double d = Double.parseDouble(s );
③ Character's getNumericValue(char ch) method can be found in the API.
5. Conversion of Date class and other data types
There is no direct correspondence between integers and Date classes, but you can use the int type to represent year, month, day, hour, minute, and seconds respectively, so that a correspondence is established between the two. When doing this conversion, you can use three forms of the Date class constructor:
①Date(int year, int month, int date): Int type represents year, month, and day ②Date(int year, int month, int date, int hrs, int min): Int type represents year, month, day, hour, and minute ③Date(int year, int month, int date, int hrs, int min, int sec): Int type represents year, month, day, hour, minute, and second There is an interesting correspondence between long integer and Date classes, that is, a time is expressed as the number of milliseconds from 0:00:00, GMT on January 1, 1970. For this correspondence, the Date class also has its corresponding constructor: Date(long date).
Get the year, month, day, hour, minute, second and week in the Date class. You can use the getYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), getDay(), and you can also understand it as converting the Date class into an int.
The getTime() method of the Date class can get the long integer number corresponding to the time we mentioned earlier. Like the wrapper class, the Date class also has a toString() method that can convert it into the String class.
Sometimes we want to get a specific format of Date, for example 20020324, we can use the following method, first introduce it at the beginning of the file,
import java.text.SimpleDateFormat;import java.util.*;java.util.Date date = new java.util.Date(); //If you want to get the format of YYYYMMDD SimpleDateFormat sy1=new SimpleDateFormat("yyyyMMDD");String dateFormat=sy1.format(date); //If you want to get year, month, day, SimpleDateFormat sy=new SimpleDateFormat("yyyyy"); SimpleDateFormat sm=new SimpleDateFormat("MM"); SimpleDateFormat sd=new SimpleDateFormat("dd");String syear=sy.format(date);String smon=sm.format(date);String sday=sd.format(date);