I believe everyone knows that Java's new keyword is instantiating an object. Yes, it is also allocating memory space for new objects.
For example, in a case like new MyDate(22, 7, 1964), his completion requires four parts:
one. Allocate memory space for the new object and store MyDate to the heap.
two. Perform initialization of display
three. Execute the constructor. The bracket parameters in the new method are passed to the constructor, and the object value is published.
Four. This variable is assigned as a reference to a new object in heap memory
In layman's terms, your new operation is actually adding a new object to the heap of memory and initializing the new object through a constructor method and storing the reference to the object in the stack.
Here I have a case that is easy to understand:
public class Pet {protected bean be = this.b();public bean b(){return new bean();}} public void test(){be.setName("Zhang San");}public void test2(){System.out.println(be.getName());}public static void main(String[] args) {People pe = new People();pe.test();pe.test2();} A parent class and a child class. Assign a value to the name through test. The output value of test2 will find that the output test is assigned to the name. Because when running the main method, the program will first compile the parent class and instantiate the be object, so the references in the subclass are the same object, but if modified to the following code:
public void test(){bean be = new bean();be.setName("Zhang San");}public void test2(){System.out.println(be.getName());}public static void main(String[] args) {People pe = new People();pe.test();pe.test2();} In the test, I new a be object, and the output is null, because the references they store in the memory stack are different. In the actual encoding process, it is best to write objects with more references in the parent class, inherit subclasses, or write them into Java's single-right lazy mode:
public class DanLi1class {//1. To implement the single-profit model, you must modify its construction method () private DanLi1class(){}//2. First, instantiate the instance by yourself private static DanLi1class dan1 = new DanLi1class();//3. To ensure that other programs access the instance Hua object of this instance, you need to define a static method public static DanLi1class danli1(){return dan1;}} This will save memory usage and enable objects to be reused, so why not do it?