Java objects and their memory controls

Source: Internet
Author: User

Zen House Moon (Http://www.cnblogs.com/yaoyinglong)

Java promises a good promise to programmers: without caring about memory recycling, Java provides an excellent garbage collection mechanism to reclaim already allocated memory.

So beginners tend to splurge on Java memory, resulting in a slow running of Java programs, the main disadvantages are:

    1. Continuously allocating memory reduces the available memory in the system, thus reducing program performance;
    2. (more importantly) a large amount of allocated memory recycling makes the burden of garbage collection heavier, reducing the running performance of the program.
1 forward Application

This means that when you define an instance member variable in Java, you must use a valid forward reference . The same two class member variables must also take a valid forward reference :

however , if one is an instance member variable and one is a class member variable, the instance member variable can always refer to a class member variable:

This is because the class member variable initialization time always precedes the time that the instance member variable is initialized . 2. Static members can be instance members

Static variables that use static modifiers belong to the class itself, and instances of the instance variable data class. In the same JVM, each class corresponds to only one class object, so class variables for a class within the same JVM require only a single piece of memory space, but each class can create multiple Java objects, so the JVM must allocate a chunk of memory space for each Java object's instance variable.

Java allows class member variables to be accessed through classes, as well as to allow class instances to access class member variables (Java is not a reasonable design)

However, Java designers, while accessing class member variables in class instances, still convert the underlying to a class to access class member variables. How to prove it?

Take a look at the anti-compilation:

The JVM uses the reference type of the Someth object to invoke the static member at the bottom, which gives the programmer a certain illusion that the call is something of its own, but that changing the value of the static member is reflected in the other objects, which is dangerous:

The value of a class member variable is modified in one instance of the class, but it is reflected in another instance of the class. 3 initialization time for instance variables

From a grammatical point of view, we can initialize an instance variable in 3 places as follows:
① defining an instance variable is a specified initial value
② specifying an initial value for an instance variable in a non-static initialization block
The ③ constructor specifies an initial value for the instance variable.
Where ① and ② are executed earlier than ③, ① and ② that are executed earlier, see that that appears earlier in the code. Such as:

This shows that class instance variables can only be initialized in the constructor, but as programmers programming, they may be placed at the definition or in non-static blocks, but the results are the same, and the JVM will extract them and put them in the constructor. 4 class Variable Initialization timing

From a grammatical point of view, you can initialize a class variable in the following two places:
① initialization when defining class variables;
② a static initialization block to specify the initial value for the class variable.
The order in which these two methods are executed is the same as the order in which they appear in the source code:

This shows that class variables can only be initialized in static blocks, but as programmers programming, can be placed at the definition can also be placed in the static fast, the results are the same, the JVM will collect them all put into the static fast. 5 Parent class constructor

Look at the following code:

This raises a question: where the sub class has not been created (because the constructor of the parent class is not finished when the display is called, how can I walk the constructor of the subclass), how is it possible to invoke its method?
Eh Isn't the class instance created by the constructor?
This is said in many books: class instances are created by the constructor.
In fact, this sentence is completely wrong. The actual situation is that the constructor is simply responsible for initializing the Java object instance variable (that is, assigning the initial value), and the memory of the object is allocated before the constructor code is executed. The values in these memory are the default values for each type.
So the above code executes the new sub (); The system has allocated a memory space for the Sub object (two memory space, a piece of I for the sub to hold the base of I (This piece of memory, the child class and the parent class share, change any one another will follow the move), The reason is that the subclass cannot completely overwrite the member variable of the parent class)
Attention:
The object is created by the new keyword, in the execution of new ... , a Java object has been built, but its variables are not initialized, and the function of the constructor is to initialize the variables. A method that does not run out of a constructor Java object can be called because it does not have any difference from a generic Java object.
Take another look at the code:

Do you feel that this is a bit confusing?
However, from the printed result, this does refer to sub, but we also know that when this is in the constructor, this refers to the Java object being initialized. How do you understand it? From the source code, this time this is in the base constructor, but the code is actually executed inside the sub () constructor, which is the code of the sub () constructor that implicitly calls the base () constructor. Thus, this refers to a sub rather than a base. Now that the problem has come again, since this refers to sub, why System.out.println ("I come from" +this.getclass () + "--" +this.i), but the result is 2? This is because, although this actually points to a sub object, it has a compiled type of base when it is in the base constructor. So the output is 2.
So we can draw the following conclusions:
When a variable (a) compile-time type and run is not the same type, through which the variable (a) accesses the instance variable of the object it refers to, the value of the instance variable is determined by the type that declares the variable (a). However, when an instance method of the object it references is called through the variable, the method behavior is determined by the object that the variable (a) actually refers to. 6 Memory control for parent-child instances

By:

1. Variables d2b and D actually point to the same object, but when they access their instance variables they output different values, which indicates that the Java object pointed to by the D2B and D variables contains two blocks of memory, not the count instance variable with a value of 2 and the count instance variable with a value of 20.
2, regardless of D, DB, d2b, as long as they point to a sub object, no matter what type they are declared to use, when invoked through these variables, the behavior of the method always shows the behavior of their actual type. However, if you access the instance variables of the objects they refer to by these variables, the values of these instance variables always show the behavior of the types used to declare those variables. This shows that Java inheritance differs in handling member variables and methods.

However, you can still call the overridden method in the parent class through Super.
Let's take a look at this piece of code:

// Parent Class  Public class Base {      privateint x=10;        Public int GetX () {          return  x;        }        Public void SetX (int  x) {          this. x = x;      }  } 
// sub-class  Public class extends Base {      public  Sub () {          this. SetX ()          }  } 
//Test Public Static voidMain (string[] args) {Base b=NewBase (); System.out.println ("I am the parent class:" +b.getx ());//-->10Base base=NewSub (); System.out.println ("I am the parent class:" +base.getx ());//-->20Sub s=NewSub (); System.out.println ("I am a sub-category:" +s.getx ());//-->20System.out.println ("I am the parent class:" +base.getx ());//-->20}

Use the JAVAP tool to view:

This shows that the subclass inherits the instance variable of the parent class, the in-memory value requests space for the variable in the parent class, and does not open up memory space for that variable in the subclass. Some people may say that you here the instance variable x is private, in fact, public is the same, do not believe the words can try.
So, we call the Setx method in the subclass. In fact, the instance variable x in the parent class is set. Because this method is inherited from the parent class. It is also possible to conclude that the parent class does not normally set a static global variable, which can be a thread-safe issue.

So using super in a subclass means using the same method that is inherited from the parent class that is stored in your own object.
Thus, the super itself does not refer to any object, it can only be counted as a token. Its role is limited to the invocation of an instance variable defined in the parent class, or the overridden method defined in the subclass, in the subclass (not the object of the subclass).
Note: Although this is the method and variable in the parent class. In fact, there is nothing to do with the parent class. Just a little bit different on the call, the other and the class own method is no different. 7 class variables for parent-child classes

Remember: Java allows you to invoke static variables of a class through an instance object
The other is the same as the instance variable. 8 final

Final-Modified variables
The final modified variable must display the specified initial value (the default value is set by the normal variable system), and the initial value can only be established in the following 3 places:

For a final variable, whether it is a class variable, an instance variable, or a local variable, as long as the variable is finalized and given the initial value (required), then it is determined when the class is compiled, then the final variable is no longer a variable, but rather a direct amount.

Local variables in the inner class
If a program needs to use a local variable in an inner class, the local variable must be decorated by the final.
But why should the local variables to be accessed in the inner class have to use the final decoration?
The reason is that for a normal local variable, its function is to stay within the method, and the local variable disappears after the method ends, but the inner class may produce an implicit "closure", and the closure will leave the local variable out of the way it exists.

Java objects and their memory controls

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.