Java New keyword Presumably everyone knows that this is an instantiation of an object. Yes, it also allocates memory space for new objects.
For example, a case of new mydate (22,7,1964), his completion requires four parts:
One. Allocates memory space for new objects and stores mydate to the heap.
Two. Perform the initialization of the display
Three. Executes the constructor. In the new method, the bracket parameter is passed to the constructor, and the value of the object is written out
Four. The variable is assigned as a reference to the new object in heap memory
In layman's terms, the operation of your new is actually adding a new object to the heap of memory and initializing the new object by constructing the method and storing the object's reference in the stack
Below I have a case, easy to understand kind of:
public class Pet {
protected Bean is = this.b ();
Public Beans B () {return
new Bean ();
}
}
public void Test () {
be.setname ("John");
}
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, a subclass that assigns a value to name by test, test2 output value you will find that the output's positive is assigned to name, because when you run the main method, the program compiles the parent class and instantiates the being object, so the references in the subclass are the same object. But if you change it to the following code:
public void Test () {
Bean is = new Bean ();
Be.setname ("John");
}
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'm new to a be object, such output is null, because they are stored in the memory stack of the reference is not the same, in the actual encoding process, the reference to more objects are best in the parent class, subclass inheritance, or write Java simple lazy mode:
public class Danli1class {
//1. To implement the simple mode, you must modify its construction method ()
private Danli1class () {
}
//2. First instantiate the instance yourself
private static Danli1class dan1 = new Danli1class ();
3. To ensure that another program accesses an instance of this instance, the Chinese object needs to define a static method public
static Danli1class Danli1 () {return
dan1
}
}
This will save memory footprint, so that objects can be reused, why not?