Java object and Memory Management

Source: Internet
Author: User

1. Memory Allocation for instance variables and class variables

Class variables: The member variables modified using static are class variables and belong to the class itself.

Instance variable: A member variable that does not use static modification is an instance variable and belongs to this class.

Since each fatigue in the same JVM only corresponds to one Class object, the Class variables of one Class in the same JVM only need one memory space.

For instance variables, if this class does not create an instance once, you need to allocate a memory space for the instance variables. Therefore, there are several instances in the program, and the instance variables need several pieces of memory space.

2. the initialization time of class variables is always before the initialization of instance variables.

Let's take a look at the following three pieces of code:

1) because both instance variables are allocated space only when the variable is created, num2 is not allocated yet, so a compilation error occurs in the forward reference.

 
 
  1. Int num = num2 + 3; // an error is returned if the forward reference is invalid.
  2. Int num2 = 2

2) because the two class variables are allocated space when the JVM loads the class, num2 is not yet allocated, so the forward reference will encounter a mutation error.

 
 
  1. Static int num = num2 + 3; // an error is returned if the forward reference is invalid.
  2. Tatic int num2 = 2

3) because the class variable num2 has allocated space when the JVM loads the class, and num has allocated space when creating the instance, num2 has been allocated successfully, therefore, the num forward reference is successful.

 
 
  1. Int num = num2 + 3; // use it correctly
  2. Static int num2 = 2;

The above three code blocks can be used to verify that the initialization time of class variables is always before the initialization of instance variables.

3. Java object initialization method and execution sequence

Java objects can be initialized in three ways: 1) constructor 2) initialization block 3) Specify the initialization value when defining variables

If these three initialization methods appear at the same time, you should note that they also have a rule on the execution sequence:

1) The static initialization block runs only once when the class creates an object for the first time, and will not run later. The non-static initialization block always runs once every time the class creates an object.

 
 
  1. Public class Test {
  2. Static {
  3. System. out. println ("execution --- static initialization code block .");
  4. }
  5. {
  6. System. out. println ("execution --- non-static initialization code block .");
  7. }
  8. Public static void main (String [] args ){
  9. For (int I = 1; I <= 2; I ++ ){
  10. System. out. println ("create the" + I + "object ");
  11. New Test ();
  12. System. out. println ();
  13. }
  14. }
  15. }
 

Running result:

2) each time the constructor creates an object, the constructor must have a chance to execute the object. At this time, the non-static initialization block will also get the opportunity and run before the constructor.

 
 
  1. Public class Test {
  2. {
  3. System. out. println ("execution --- non-static initialization code block .");
  4. }
  5. Public Test (){
  6. System. out. println ("execution --- constructor .");
  7. }
  8. Public static void main (String [] args ){
  9. For (int I = 1; I <= 2; I ++ ){
  10. System. out. println ("create the" + I + "object ");
  11. New Test ();
  12. System. out. println ();
  13. }
  14. }
  15. }
 

Running result:

3) when defining variables, the execution sequence of the specified initialization values and the initial values in the initialization block is the same as that in the source program.

Verification Code 1:

 
 
  1. Public class Test {
  2. String I = "specifies the initialization value when defining a variable ";
  3. {
  4. I = "initial value specified in the initialization block ";
  5. }
  6. Public static void main (String [] args ){
  7. For (int I = 1; I <= 2; I ++ ){
  8. System. out. println ("create the" + I + "object ");
  9. System. out. println (new Test (). I );
  10. System. out. println ();
  11. }
  12. }
  13. }

Running result

Verification Code 2:

 
 
  1. Public class Test {
  2. {
  3. I = "initial value specified in the initialization block ";
  4. }
  5. String I = "specifies the initialization value when defining a variable ";
  6. Public static void main (String [] args ){
  7. For (int I = 1; I <= 2; I ++ ){
  8. System. out. println ("create the" + I + "object ");
  9. System. out. println (new Test (). I );
  10. System. out. println ();
  11. }
  12. }
  13. }

Running result:

4. Memory Control for parent and child instances

In general, internal classes are not used for verification, but they are all the same. I am lazy, so I used internal classes. Thank you)

1) when the subclass overrides the parent class method, the parent class only calls its own method for overwriting the quilt class.

 
 
 
  1. public class Test{ 
  2.      class Base { 
  3.          Base() { 
  4.              this.info(); 
  5.          } 
  6.          public void info() { 
  7.              System.out.println("Base"); 
  8.          } 
  9.          public void getInfo() { 
  10.              info(); 
  11.          } 
  12.      } 
  13.       
  14.      public class Child extends Base{ 
  15.          @Override 
  16.          public void info() { 
  17.              System.out.println("Child"); 
  18.          } 
  19.      } 
  20.       
  21.      public static void main(String[] args) { 
  22.          Test test = new Test(); 
  23.          Base base = test.new Child(); 
  24.          base.info(); 
  25.          base.getInfo(); 
  26.      } 
  27.  } 

Running result:

2) The above is a manifestation of the method in polymorphism, but the method has polymorphism and the instance variable has no polymorphism.

To explain the following sentence: "methods are polymorphism and variables are not polymorphism" means that, in any case, the parent class only calls its own method for overwriting the quilt class. The variables are different. Assume that both the parent class and the subclass have instance variables with the same variable name, the value obtained from the instance variables accessed by the parent class is its own, not its subclass. After the downward transformation, the instance variables accessed through the subclass obtain their own values rather than the parent class.

In many books or instructional videos, when creating a subclass Object, Java will continue to find the Object along the inheritance structure, and then execute the constructor from the Object. Execute the constructor of the parent class first, and then create a member variable pointing to its parent class in its subclass. In fact, this statement is wrong. The system does not really create a parent class object, but not only saves its own instance variables, but also all instance variables of its parent class.

 
 
  1. Public class Test {
  2. Class Base {// parent class
  3. Int I = 2;
  4. }
  5. Public class Child extends Base {// subclass
  6. Int I = 20;
  7. }
  8. Public static void main (String [] args ){
  9. Test test = new Test ();
  10. Child child = test. new Child ();
  11. Base base = child;
  12. System. out. println ("Base. I:" + base. I );
  13. System. out. println ("Child. I:" + child. I );
  14. }
  15. }

Running result:

5. final Modifier

Final is determined at compilation, which is equivalent to a direct volume.

1) final modified instance variable Assignment time:

Specify the initial value when defining final instance variables

The initial value specified for the final instance variable in the non-static initialization module

Specify the initial value for the final instance variable in the constructor.

2) final variable Assignment time:

Specify the initial value when defining final Variables

The initial value specified for the final instance variable in the static initialization module.

Edit recommendations]

  1. Java Exception Handling
  2. Java security model Introduction
  3. Explore the Java language and Lambda expressions in JVM
  4. Java online tutorial-Interface
  5. Java serialization and JSON serialization Competition

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.