A Class loading process
In java class loading means to load the information into the memory classes . And only the first time will be loaded when using this class.
A category information includes the following components:
- Class variables (static variables);
- Class initialization code:
- defining static assignment statement when the variable
- a static initializer block - Class methods (static methods);
- Instance variables;
- Example initialization code:
- assignment statement when the instance variables defined
- Example initializer block
- Constructor - Examples of the method;
- The parent class information reference.
Class loading process includes:
- Memory allocation information stored class;
- The default value assigned to the class variable;
- Load the parent class;
- Set parent-child relationship;
- Perform class initialization code.
Stack and heap memory is divided into, the stack for local variables, the storage dynamically allocated heap object , there is a memory area called method area, store information such .
After loading, java method area will have a copy of the information in this class.
Examples are as follows:
public class Base {
public static int s;
private int a;
static {
System.out.println("基类静态代码块,s:" + s);
s = 1;
}
{
System.out.println("基类实例代码块,a:" + a);
a = 1;
}
public Base() {
System.out.println("基类构造方法,a:" + a);
a = 2;
}
protected void step() {
System.out.println("base s:" + s + ",a:" + a);
}
public void action() {
System.out.println("start");
step();
System.out.println("end");
}
}
public class Child extends Base {
public static int s;
private int a;
static {
System.out.println("子类静态代码块,s:" + s);
s = 10;
}
{
System.out.println("子类实例代码块,a:" + a);
a = 10;
}
public Child() {
System.out.println("子类构造方法,a:" + a);
a = 20;
}
protected void step() {
System.out.println("child s:" + s + ",a:" + a);
}
public static void main(String[] args) {
System.out.println("---- new Child()");
Child c = new Child();
System.out.println("\n---- c.action()");
c.action();
Base b = c;
System.out.println("\n---- b.action()");
b.action();
System.out.println("\n---- b.s:" + b.s);
System.out.println("\n---- c.s:" + c.s);
}
}
Memory layout as shown:
Second, the process of object creation
After the class is loaded, the process of creating an object, including:
- Allocate memory;
- Assign default values for all instance variables;
- Examples of code execution.
Each object instance variable is stored in addition to the class, the class also holds the actual information to be referred.
Examples are as follows:
Child Child new new C = (); Child objects will be newly created reference to a variable c, and Base b = c; b will also reference the Child object.
After creating and assigning memory layout:
reference variable c and b allocated on the stack, they point to the same heap Child objects. Child objects stored in the method area Child type of address, there is a Base instance variables and instance variables Child a.