Java objects and its memory management

Source: Internet
Author: User
Tags instance method md5 hash variable scope

Memory management in Java is divided into two areas:

Memory allocation: Refers to the memory space allocated by the JVM to the object in the heap space when a Java object is created.

Memory reclamation: When a Java object loses its reference and becomes garbage, the garbage collection mechanism of the JVM automatically cleans up the object and reclaims the memory occupied by the object.

Although the JVM built-in garbage collection mechanism, but still can lead to memory leaks, resource leaks, etc., so we can not unscrupulous to create objects. In addition, the garbage collection mechanism is done by a background thread and is also very performance-intensive.

1. Instance variables and class variables

Variables in Java programs can be broadly divided into member variables and local variables. The local variables can be divided into the following three categories:

Formal parameter: A variable defined in the method name that the method caller is responsible for assigning to, and dies as the method ends.
In-Method local variables: variables defined within a method must be initialized within a method. It comes into effect from the completion of initialization and dies as the method ends.
Local variables within a code block: variables defined within a block of code that must be initialized within a block of code. Takes effect from the completion of initialization and dies as the code block ends.
The action time of local variables is very short, they are in the stack memory.

Variables defined within a class are member variables. If you use the static modifier, it is either a static variable or a class variable, otherwise it becomes a non-static variable or an instance variable.

Static

His role is to program the instance members into class members. You can only modify member parts that are defined in a class, including variables, methods, internal (enumerations and interfaces), and initialization blocks. cannot be used to decorate external classes, local variables, local inner classes.

Member variables that use the static modifier are class types, belong to the class itself, and are not decorated with instance variables that belong to instances of the class. In the same JVM, each class can create multiple Java objects. Each class in the same JVM corresponds to only one class object, and the class variable occupies only a single memory space, but the instance variable allocates a chunk of memory space each time it is created.

Class person{string name;int age;static int eyenum;public void info () {System.out.println ("My name is:" + name  + ", my Age is:" + age);}} public class Fieldtest {public static void main (string[] args) {//class variable belongs to the class itself, as long as the class initialization is complete,    //The program can use class variables. person.eyenum=2; SYSTEM.OUT.PRINTLN ("Eyenum attribute of Person:"            +person.eyenum);//Access Eyenum class variable through the person class//Create first Person object// The Eyenum class variable of the person class is accessed by P p=new person ();p. Name= "Hoo";p. age=33; SYSTEM.OUT.PRINTLN ("Access the Eyenum class variable through a P variable:"            +p.eyenum);p. info ();//Create a second person object person P2 = new Man ();    P2.name = "Po";    P2.age =;    P2.info ();     p2.eyenum=4;//modifies the Eyenum class variable of the person class by P2//accesses the Eyenum class variable    System.out.println (") for the person class by P, P2, and person, respectively. Access the Eyenum class variable through the P variable: "            + p.eyenum);        System.out.println ("Access Eyenum class variables by P2 variable:"            + p2.eyenum);        SYSTEM.OUT.PRINTLN ("Access the Eyenum class variable through the person class:"            + Person.eyenum);}}

The memory allocations in the code are as follows:

When the person class is initialized and the class variable is initialized, no matter how many person objects are created, the system no longer allocates memory for Eyenum, but allocates memory and initializes the name and age. When the Eyenum value is changed, access to the Eyenum value is changed with each person object.

1). Initialization of instance variables

For instance variables, it belongs to the Java object itself, and each time the program creates a Java object it allocates memory space and initializes it.

Instance variable initialization place:

When you define an instantiated variable;
In a non-static initialization block;
The constructor.
The first two are executed earlier than the third, and the first two are executed in the same order as they were in the program. Their three functions are exactly similar, compiled and extracted into the constructor, and before all statements, the order in which variables are assigned and the initialization blocks are assigned is consistent with them in the source code.

You can use the JAVAP command to view the mechanism of the Java compiler:

Usage: JAVAP <options> <classes> among them, possible options include:-Help--help-? Output this usage message-Version
Version Information-V-verbose
Output additional Information-L
Output line number and local variable table-Public
Show only public classes and members-Protected
Show protected/Public classes and Members-Package
Show packages/protected/Public classes
and members (default)-P-private
Show all classes and members-C
Disassembly of code-s
Output internal type signature-SysInfo
That shows the class that is being processed.
System Information (path, size, date, MD5 hash)-constants
Show final Constants-classpath <path>
Specify where to find user class files-CP <path>
Specify where to find user class files-Bootclasspath <path>
Overwrite the location of the boot class file

2). Initialization of class variables

Class variables are part of the Java class itself and are initialized each time it is run.

Initialization of class variables:

Initialization when defining class variables;
Initialize in static code block
The following code, on the surface of the output is: 17.2, 17.2, but the actual output is: -2.8,17.2

Class price{//member is the price instance final static price instance=new price (2.8);//define a class variable again. Static double initprice=20;//The Currentprice instance variable that defines the price, double currenprice;public price (double discount) {// Calculates the instance variable Currenprice=initprice-discount according to the static variable;}} public class Fieldtest {public static void main (string[] args) {//Access Currentprice instance variable through the instance of price System.out.println (Price.INSTANCE.currenPrice); Price P=new price (2.8);//explicitly create price instance System.out.println (P.currenprice);//Access Currentprice instance variable through previously created price instance}}

  

The first time you use price, the program initializes it into two stages:

(1) The system allocates memory space for class variables;

(2) Initialize the variables in the initialization code order.

The result here is: -2.8,17.2

Description: Initializing the first stage, the system allocates memory space for the Instance,initprice two class variables, their default values are null and 0.0, and then the second stage assigns them the values. To call Price (2.8) When assigning a value to INSTANCE, create a price instance, assign a value to the Currentprice, at which point the Initprice is not assigned, that is, with his default value of 0, then the Currentprice value is-2.8, then the program will again Initprice is assigned a value of 20, but it has no effect on Currentprice instance variables.

2. Parent Class Builder

In Java, when you create an object, you first call the non-static initialization block of each parent class, the constructor (always starting with object first), and then initialize with the non-static initialization blocks and constructors of this class. You can make a display call with Super when the parent class is called, or you can call it implicitly.

When you call the parent class constructor in a subclass, there are several scenarios:

Subclass constructor The first line of code is to use Super () to display the call to the parent class constructor, the corresponding constructor is called according to the super passed parameters;
The first line of code for the subclass constructor is to use this () to display the constructor that is overloaded in this class, and the corresponding constructor is called according to the parameter passed in this.
There is no this and super in the subclass constructor, and the parent class is implicitly called without a parameter constructor before the subclass constructor is executed.
Note: Both super and this are display call constructors that can only be used in the constructor, and must be in the first row, with only one of them, and can be called at most once.

In general, a subclass object can access an instance variable of the parent class, but the parent class cannot access the child class because the parent class does not know which subclass it will inherit from, and what method the subclass will add. However, in extreme cases, the parent class can access the child class variables in the case of the following instance code:

Class Base{private int I=2;public base () {//this: Runtime is a driver type, compile-time is base type, here is Driver object This.display ();} public void display () {System.out.println (i);}} Inherit Base Derived Subclass class Derived extends Base{private int i=22;public Derived () {i=222;} public void display () {System.out.println (i);}} public class Fieldtest {public static void main (string[] args) {//Create Derived constructor Create instance new Derived ();}}

  

When the above code executes, the output is not 2, 22, or 222, but 0. The parameterless constructor of base is implicitly called before calling Derived's constructor, initializing I= 2, at which point the output this.i is 2, which accesses the instance variable in the base class, but when This.display () is called, the behavior of the driver object is displayed. For the driver object, its variable i has not yet been assigned an initial value, just to open up memory space for it, with a value of 0.

In Java, the constructor is responsible for initializing the instance variable (that is, assigning the initial value), and before executing the constructor, the object's memory space has been assigned the default value for the type of things they have stored in memory.

In the preceding code, the compile-time type of the variable that occurred is different from the run-time type. When you access an instance variable of an object that he refers to by using that variable, the value of the instance variable is determined by the type that declares the variable, and when an instance method of the instance object that it refers to is invoked through that variable, the method is determined by the object it actually refers to.

When a subclass overrides a parent class method, there is also the case of a method such as a parent class invocation, which is easily understood by the following code.

Class Animal{private String desc;public Animal () {This.desc=getdesc ();} Public String GetDesc () {return "Animal";} Public String toString () {return  desc;}} public class Wolf extends Animal{private string name;private double weight;public Wolf (string name, double weight) {THIS.N Ame = Name;this.weight = weight;} Override the GetDesc () method of the parent class @overridepublic String GetDesc () {return "wolf[name=" + name + ", weight="            + weight + "]";  Output: Wolf[name=null, weight=0.0]}public static void Main (string[] args) {System.out.println (New Wolf ("Wolf", 2.9));}

  

3. Memory control for parent-child instances

Inheritance in Java is different when working with member variables and methods. If a subclass overrides a method of the parent class, it completely overrides the parent class's method and moves it to the child class, but if it is an instance variable of exactly the same name, it will not be overwritten and will not be moved from the parent class to the child class. So, for a variable of a reference type, if you access the instance variable of the object that he refers to, the value of the instance variable depends on the type that declares the variable, and when the method is called, it depends on the type of object it actually refers to.

In inheritance, an instance of a child class of memory holds an instance of a variable of the parent class.

Class Base{int count=2;} Class Mid extends Base{int count=20;} public class Sub Extends mid{int count = n, public static void main (string[] args) {    //Create a Sub object sub S=new sub ();// The sub object is transformed upward and assigned to the mid, base type variable mid s2m=s; Base s2b=s;//accesses the Count instance variable System.out.println (s.count) by 3 variables respectively;    Output:        System.out.println (s2m.count);    Output:        System.out.println (s2b.count);    Output: 2}}

In-Memory:

There is only one sub object in memory, and there are no mid and base objects, but there are 3 instance variables for count.

A variable that hides a parent class in a subclass can be obtained through super, which can also be accessed by Super for class variables.

4.final modifier

Final Cosmetic Range:

Modifier variable, cannot be re-assigned after the initial value is assigned;
Modification method, cannot be rewritten;
Decorated class, you cannot derive a subclass.
For a final type of variable, initialization can be in: definition, non-static code block, and constructor, and for a class variable of the final type, initialization can be in both definition and static code blocks.

When an initial value is specified when a variable of the final type is defined, the variable is essentially a "macro variable", and the compiler substitutes the variable directly with its value.

If a local variable is used internally, it must be specified as the final type. The normal variable scope is the method, and as the execution of the method ends, the local variable disappears, but the inner class may produce an implicit "closure", leaving the local variable out of the method where it exists. The scope of the local variable may be expanded internally, and if the local variable accessed internally does not have a final decoration, it can be arbitrarily modified so that it will cause confusion, so the compiler requires that local variables that are accessed internally must use the final decoration.

Java objects and its memory management

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.