The creation of an object basis of java

Object creation

class A {
int v1 = 1;
static int v2 = 2;
static {}
A() {}
}
class B exntends A {
int v3 = 3;
static int v4 = 4;
static {}
B() {}
}

A first use ▶ and B

  1. Static variable load parent, the parent class to allocate memory
  2. Load subclass allocate memory for static variables subclass
  3. Performing parent class assignment operator static variables, and static initialization block
  4. Performing assignment operator subclass static variables, and static initialization block

▶ create an instance

  1. Create a parent class instance, the parent class's instance variables to allocate memory
  2. Create a subclass instance, allocates memory for the instance variables of a subclass
  3. Assignment operations performed parent instance variables
  4. Performing parent class constructor
  5. Assignment operations performed in the sub-class instance variables
  6. Constructor method performed subclass

Code Example:

ublic class Test1 {
public static void main(String[] args) {
System.out.println("第一次创建实例,会首次加载类");
new B();
System.out.println("第二次创建实例,不会加载类");
new B();
}
}
class A{
int v1 = 1;
static {
System.out.println("A静态块, A.v2="+A.v2+", B.v4="+B.v4);
}
static int v2 = 2;
A() {
System.out.println("A构造方法");
}
}
class B extends A {
int v3 = 3;
static int v4 = 4;
static {
System.out.println("B静态块,B.v4"+B.v4);
}
B() {
System.out.println("B构造方法");
}
}
Released six original articles · won praise 11 · views 187

Guess you like

Origin blog.csdn.net/qq_44799169/article/details/104582086