Java's new Keyword and javanew keyword
Java's new keyword must be known as an object. Yes, it also allocates memory space for new objects.
For example, in the case of new MyDate (1964,), four steps are required to complete the process:
I. Allocate memory space for the new object and store MyDate to the heap.
II. Execute display Initialization
3. Execute the constructor. The brackets in the new method are passed to the constructor.
4. This variable is assigned a reference to a new object in heap memory.
In layman's terms, your new operation is actually adding a new object to the memory heap, initializing the new object through the constructor, and storing the reference of this object in the stack.
The following is 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 subclass assign a value to name through test. test2 outputs a value and you will find that test assigns a value to name, because when running the main method, the program will first compile the parent class and instantiate the be object, so the reference in the subclass is the same object, but if it is 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 test, I added a new be object, and the output is null, because the references they store in the memory Stack are different. In the actual coding process, it is best to write a reference to a large number of objects in the parent class, subclass inheritance, or java's single-profit lazy mode:
Public class DanLi1class {// 1. to implement the Single-profit mode, you must modify its constructor () private DanLi1class () {}// 2. first, instantiate the private static DanLi1class dan1 = new DanLi1class (); // 3. to ensure that other programs access the China object of the instance, a static method public static DanLi1class danli1 () {return dan1 ;}} needs to be defined ;}}
In this way, memory usage is reduced, and objects can be reused.