Object-Oriented Programming (III)-memory analysis during program execution and Object-Oriented Programming
Memory analysis (SxtStu. java)
Stack):
Storage: local variables;
Heap):
Stores new objects;
Method):
Storage: class information (CODE), static variables, constant pools (string constants), etc.
Stack features: automatic allocation of continuous space, followed by first-in-first-out; generally placed with local variables
Heap features: discontinuous space; placement of newly created objects;
Perform the following analysis:
The memory analysis diagram is as follows:
Now we analyze Figure 2:
Student class:
Public class Student {// static data String name; int id; int age; int weight; Computer computer; // Each Student has a Computer // dynamic behavior public void study () {System. out. println (name + "");} public void sayHello (String sname) {System. out. println (name + "" + sname + ", Hello ~ ");}}
Computer Class:
Public class Computer {String brand; // brand int cpuSpeed; // cpu}
Then:
Public class Test2 {public static void main (String [] args) {Student s1 = new Student (); s1.name = "Xiong 'er"; s1.age = 18; computer c = new Computer (); c. brand = "Lenovo"; c. cpuspeed= 100; s1.computer = c; // c. brand = "Dell ";
System.out.println(s1.computer.brand); } }
The memory analysis is as follows:
Note: If you add the comment section "c. brand =" Dell ";", s1.computer. brand finally outputs "Dell" because they point to the same place.