Java memory management is divided into two areas: memory allocation and Memory recycling
The inability to squander Java's memory allocations can result in inefficient Java programs:
Constant memory allocation reduces the amount of available memory in the system, thus reducing program performance.
The large amount of memory that has been allocated has increased the burden of garbage collection and reduced the running performance of the program.
One. memory allocations for instance variables and class variables
The variables of the Java program are broadly divided into member variables and local variables. Local variables are divided into 3 categories:
Formal parameter: a local variable defined in a method that is assigned by the method caller and disappears with the end of the method
Local variables within a method: Local variables defined within a method must be displayed initialized within the method. This variable takes effect from the completion of initialization and disappears with the end of the method.
Local variables within a code block: Local variables defined in a block of code that must be displayed initialized within a block of code. This type of local variable takes effect from the completion of initialization and disappears with the end of the block of code.
Local variables have short action times and are stored in the stack memory of the method.
A variable defined in a class is a member variable , which is also known as an instance variable, a non-static variable if the defined member variable is not using the static modifier, or a static variable with a static member variable.
Static can only modify the member parts defined in the class, including member variables, methods, inner classes, fast initialization, and internal enumeration classes.
int num1=num2-1;
int num2=3;
This will result in an illegal forward reference, because the num2 value is used in the first row to assign a value to NUM1, but Num2 is assigned in the second row.
int num1=num2-1;
static int num2=3;
This makes no mistake, because NUM1 is an instance variable, and num2 is a class variable,the initialization time of a class variable is always before the initialization time of the instance variable, so correct.
A member variable that uses the static modifier is a class variable that belongs to the class itself; A variable that does not use static is an instance variable that belongs to an instance of the class. Because each class in the same JVM corresponds to only one class object, the class variables of a class within the same JVM require only a single piece of memory space, but for instance variables, each time an instance is created, it is necessary to allocate a piece of memory space for the instance variable. In other words, there are several instances in the program, and the instance variables require a few blocks of memory space.
Class Person
{
String name;
int age;
static int eyenum;//class variable
}
public class Fieldtest
{
public static void Main (string [] args)
{
person.eyenum=2; Initializes the class variable with the person
Person P=new person ();
P.name= "Pig";
p.age=300;
Person P2=new person ();
P2.name= "Monkey King";
p2.age=500;
p2.eyenum=3; }
}
Java allocates memory in the following cases:
When a program creates an object p for a person, the system no longer allocates memory space for the Eyenum class variable, but only initializes the instance variable for the person object, because the instance variable belongs to the person instance, and the class variable belongs to the person class itself.
When the Eyenum class variable of the person class is modified, the program accesses the Eyenum class variable through the P,p2,person class and outputs 3.
2. Initialization time for instance variables
A program can initialize instance variables in 3 places:
Specify an initial value when defining an instance variable;
Specifies the initial value of an instance variable in a non-static initialization block;
Specifies initialization for instance variables in the constructor;
The first two are executed earlier than the third. However, the first to second order of execution is the same as the order in which they are arranged in the source program.
Class Cat
{
String name;
int age;
Public Cat (string name, Int. age)
{this.name=name;
This.age=age;
}
{weight=2.0;}
Double weight=2.3;
}
public class Fieldtest
{
public static void Main (string [] args)
{
Cat cat1=new Cat ("Kitty", 2);
Cat Cat2=new Cat ("Niko", 3);
}
}
The program executes a non-static initialization block in cat (because there is no class variable in the Class), and then calls the Cat class's constructor to initialize the cat instance, andthe value of weight is 2.3 instead of 2. This is because the initial value specified in the initialization, the initial value specified when the weight is defined, are the initialization operations performed on the instance variable, and they are executed in the same order as they were arranged in the source code . Therefore, the initialization value specified for weight in the initialization block is overwritten each time by 2.3.
Summary : The initial value defined when the instance variable is defined, the initial value specified for the instance variable in the initialization block, the initial value specified for the instance variable in the constructor, and the role of the three are exactly the same, and are used to specify the initial value for the instance variable. After the compiler has processed them, the corresponding assignment statements are merged into the constructor, and during the merge, the statements in the constructor are followed by the preceding statements, and the first two cases are executed in the same order as they were in the source code.
3. Initialization time for class variables
A program can initialize a class variable in 2 places:
Specifies the initial value when defining a class variable;
Specifies the initial value of the class variable in the static initialization block ;
When the program executes, it first allocates memory space for all class variables, and then executes the initial values specified in the static initialization block and the initial values specified when defining class variables in the order in which they are arranged in the source code.
Second, the parent class constructor
When creating any Java object, the program will always call each parent class non-static initialization block, the parent class constructor to perform initialization, and finally call the non-static initialization block of this class, the constructor performs initialization.
Class creature
{
{
SYSTEM.OUT.PRINTLN ("Non-static initialization block of Cresature");
}
Public creature ()
{
System.out.println ("Cresature-free constructor");
}
Public creature (String name)
{
This ();
System.out.println ("Cresature" constructor with the name parameter, name parameter: "+name);
}
}
Class Animal extends Creature
{
{
SYSTEM.OUT.PRINTLN ("Non-static initialization block of animal");
}
Public animal (String name)
{
Super (name);
System.out.println ("Animal with parametric nmae");
}
Public Animal (String name, Int. age)
{
This (name);
System.out.println ("Animale with two parameters of the constructor");
}
}
Class Wolf extends Animal
{
{
System.out.println ("Wolf's non-static initialization block");
}
Public Wolf ()
{
Super ("Grey Wolf", 3);
System.out.println ("Wolf's non-parametric constructor");
}
Public Wolf (double weight)
{
This ();
System.out.println ("Wolf's constructor with weight parameter" +weight);
}
}
public class Inittest {
public static void Main (string[] args)
{
New Wolf (5.6);
}
}
The above program defines three classes, all of which contain non-static initialization and constructor components. The results of the implementation are as follows
Non-static initialization block of Cresature
Cresature constructor for the non-parametric
Cresature the constructor with the name parameter, name parameter: Grey Wolf
Non-static initialization block of animal
Animal constructor with parametric Nmae
Animale with two parameters of a constructor
Wolf's non-static initialization block
Wolf's argument-free constructor
Wolf's constructor with weight parameter 5.6
As long as the program creates a Java object, the system always invokes the initialization of the topmost parent class, including the initialization block and the constructor, then the initialization of the parent class, and then the initialization of the class, and the last instance of this class is returned. As for calling the parent class there is a constructor initialization, which is divided into several situations:
The first line of code for the subclass constructor execution uses the super () display to call the parent class constructor
The first line of code for the subclass constructor execution uses this () to display the overloaded constructors that call this class, and the system determines another constructor for this class based on the list of arguments passed in this call
There is neither super nor this in the subclass, the parameterless constructor is called implicitly in the parent class
Both super and this can be used only in the constructor, and must be in the first row in the constructor, with only one in the constructor, and one at most.
2.2 Accessing instance variables of child class objects
A method of a subclass can access an instance variable of the parent class because the child class inherits the parent class. The parent class's method cannot access the child class's instance variable because the parent class cannot know where the subclass inherits. However, in some extreme cases, it is possible for the parent class to access the child class variable.
The constructor is only responsible for initializing the Java object instance variable, that is, assigning a value, the memory that the object occupies before executing the constructor code is already allocated, and these in-memory values are null by default. When this is in the constructor, this represents the Java object being initialized.
When a variable has a compile-time and run-time type that accesses an instance variable of the object it references, the value of the instance variable is determined by the type that declares the variable, but by invoking an instance method of the object it references, the behavior of the method is determined by the object it is actually referencing.
2.3 Method of calling the quilt class again
In general, a parent class cannot call a method of a subclass, but there is a special case, but after the method of the subclass method is re-parented, the parent class simply calls its own method, but actually the method that called the subclass.
Class Animal
{
Private String desc;
Public Animal ()
{
This.desc=getdesc ();
}
Public String GetDesc ()
{
return "Animal"; 2
}
Public String toString ()
{
return desc;
}
}
Class Wolf extends Animal
{
private String name;
private double weight;
Public Wolf (String name, double weight)
{
This.name=name; 3
This.weight=weight;
}
@Override
Public String GetDesc ()
{
Return "Wolf[name=" +name+ ", weight=" +weight+ "]";
}
}
public class Inittest {
public static void Main (string[] args)
{
System.out.println (New Wolf ("Grey Wolf", 32.3));//1
}
}
The result of the above program output is wolf[name=null,weight=0.0]
Subclasses rewrite the GetDesc () function of the parent class, when the program executes, the first is to execute a 1-part program, which is called the constructor to initialize the Wolf object, but the first call to the parent class of the parameterless constructor first initialized, that is, the second part of the program, before 3 is executed, The function of the parent class in the parameterless constructor the quilt class re-calls the subclass method, and then outputs the result. After executing the 2-part program, a 3-part program is executed, and the Wolf object assigns name, weight, but the value of the DESC instance variable is wolf[name=null,weight=0.0]
To avoid this unwanted result, you should avoid calling the quilt class override method in the constructor of the animal class, so instead
Class Animal
{
Private String desc;
Public String GetDesc ()
{
return "Animal"; 2
}
Public String toString ()
{
return GetDesc ();
}
}
The result will be what you expect. Wolf[name= Wolf, weight=32.3]
2.3 Memory control for parent-child instances
Class Base
{
int count=2;
public void display ()
{
System.out.println (This.count);
}
}
Class derived extends base
{
int count=20;
@Override
public void display ()
{
System.out.println (This.count);
}
}
public class Inittest {
public static void Main (string[] args)
{
Base b=new base ();1
System.out.println (B.count);
B.display ();
Derived d= new derived ();
System.out.println (D.count);
D.display ();
Base bd=new derived ();
System.out.println (Bd.count);
Bd.display ();
Base Db2=d;
System.out.println (Db2.count);
}
}
The result of the output is
2
2//Output result no doubt, declare a base variable b
20
20//is no problem.
2
20//declares a base variable, but assigns the derived object to the variable. The system automatically transitions upward to ensure that the program is correct. Accessing the Count instance variable directly from DB, the output will be the value of the count instance variable of the base (declared type) object, and if the display () method is called through DB, the method will exhibit the behavior of the derived (runtime type) object.
2//at this point DB2 and D both point to the same object, but DB2 is a base variable, so when it accesses the instance variable, it shows the behavior of the declaring type, so it is 2 instead of 20.
But whether it is a D variable or a db,db2, as long as they actually point to a derived object, no matter what type they are declared on, when the method is called through these variables, the method always shows the behavior of the derived object, and when the instance variable is accessed, the behavior of declaring the variable type is manifested.
If the child class overrides the parent class method, it means that the method defined in the subclass completely overrides the same name method in the parent class, and the system will not be able to transfer the methods in the parent class to the subclass. There is no such phenomenon for instance variables, and this instance variable does not overwrite the parent class even if there are instances of the same instance variable in the child class. So there is a difference between the inherited member variable and the inheritance method.
2.3 Class variables for parent-child classes
Because class variables belong to the class itself, and instance variables are objects, class variables are less complex. Java allows access to class variables through objects, and if the Count class variable defined in the parent class is accessed directly in the subclass, the parent class name can be used directly. Count or Super.count, the previous one is recommended.
2.4 Final modifier
Final can modify the variable, after the final modified variable is assigned the initial value, it cannot be re-assigned value
Final can modify the method, the final modified method cannot be overridden
Final can be decorated with classes, classes that are decorated cannot derive subclasses
For a normal instance variable, the Java program can perform its default initialization, which is to specify the value of the instance variable as the default initial value of 0 or NULL, but for the final instance variable, the programmer must display the specified initial value.
You can only specify the initial value for the final variable in 3 places;
Specifies the initial value when defining the final instance variable;
Specifies the initial value for the final instance variable in a non-static initialization block;
The initial value specified in the constructor for the final instance variable.
For the final class variable, you must also display the specified initial value and initialize it only at 2:
When defining the final class variable
Assigning a value to the final class variable in a static initialization block
For a final variable, whether it is a class variable, an instance variable, or a local variable, as long as the variable is defined with the final modifier decorated and an initial value is specified when the final class variable is defined, and the initial value is determined at compile time, Then this final variable is essentially no longer a variable, but a direct amount.
One important use of the final modifier is to define a "macro variable." If the assigned expression is just a basic arithmetic expression or string join operation, no ordinary variable is accessed, and the calling method will treat it as a macro variable.
However, for a final instance variable, the effect of a "macro variable" is only specified when the variable is defined by the initial value.
public class Inittest {
public static void Main (string[] args)
{
String s1= "Lai yuppies";
String s2= "Lai" + "yuppies";
System.out.println (S1==S2);
String str1= "Lai";
String str2= "yuppies";
String s3=str1+str2;
System.out.println (S1==S3);
}
}
The result of the output is true false
S1 is a direct volume, the value of S2 is two string direct connection operation, because the compiler can determine the value of S2 in the compilation phase, so the system will let S2 directly to the string pool in the cache "Lai yuppies" string. STR1,STR2 is a two variable, and at compile time, the value of S3 cannot be determined, so it is false.
The str1,str2 can be decorated as a final type.
If a program needs to use a local variable in an anonymous inner class, the local variable must be decorated with the final modifier.
Java requires that all local variables accessed by the inner class use the final decoration reason: For local variables, its scope stays in the method, and when the execution method ends, the local variable disappears, but the inner class may produce an implicit "closure", The closure will keep the variable out of the way it resides.
Java Objects and memory