[Javase Study Notes]-6.3 memory embodiment of Objects
In this section, let's take a simple look at what the object looks like in the memory and how it is reflected.
The test code in the preceding section is used as an example.
We have analyzed the memory allocation of the function. When the code is run, the main function is loaded to allocate a space for the main function in the stack memory;
Then run the first line of the function statement, Car myCar = new Car ();
Load the local variable myCar to the stack memory, allocate space in the heap memory through new, and then assign the address to the variable myCar;
Let's see if this is the case.
Class CarDemo {public static void main (String [] args) {// create a car instance in the calculation using the new keyword. car myCar = new Car (); // myCar is a reference variable of the class type, pointing to the object of this class. system. out. println (myCar );}}Result:
We can see where myCar is. Here we are the garage of our car. It is in the 139a55 location.
In the above heap memory, the property variables num, color, and brand of the object will be initialized by default because the variables in the heap memory will be initialized by default;
Num = 0, color = null, brand = null;
In this case, if we run myCar. start () directly instead of 2-4 statements, we can see the result as follows:
Class CarDemo {public static void main (String [] args) {// create a car instance in the calculation using the new keyword. car myCar = new Car (); // myCar is a reference variable of the class type, pointing to the object of this class. // myCar. num = 4; // myCar. color = "red"; // myCar. brand = "BWM"; myCar. start (); myCar. run (); // the content of the object to be used, possibly through the object. member Form to complete the call .}}Result:
We can see that the three attributes are initialized by default. That is to say, we didn't assign values to the attributes, and the system will create an empty car for us.
Then let's take a look at what our car looks like after the assignment:
Class CarDemo {public static void main (String [] args) {// create a car instance in the calculation using the new keyword. car myCar = new Car (); // myCar is a reference variable of the class type, pointing to the object of this class. myCar. num = 4; myCar. color = "red"; myCar. brand = "BWM"; myCar. start (); myCar. run (); // the content of the object to be used, possibly through the object. member Form to complete the call .}}
Result:
We can see that the program will assign values to the attributes num, color, and brand respectively. That is to say, we get a complete BMW car, and the address of the car is not changed, or the address value in the original heap memory.
Similarly, if we create multiple car instances, the loading process in the memory is the same, they all have their own space and corresponding addresses.