1. 程式人生 > >Java類的加載和對象創建流程的詳細分析

Java類的加載和對象創建流程的詳細分析

spa java類 parent str pac run 實例 public font

相信我們在面試Java的時候總會有一些公司要做筆試題目的,而Java類的加載和對象創建流程的知識點也是常見的題目之一。接下來通過實例詳細的分析一下:

package com.test;

public class Parent {

int a = 10;
static int b =11;
//靜態代碼塊
static {
System.out.println("parent靜態代碼塊:b=" + b);
b++;
}
//代碼塊
{
System.out.println("Parent代碼塊:a=" + a);
System.out.println("Parent代碼塊:b=" + b);
b++;
a++;
}
//無參構造函數
Parent(){
System.out.println("Parent無參構造函數:a=" + a);
System.out.println("Parent無參構造函數:b=" + b);
}
//有參構造函數
Parent(int a){
System.out.println("Parent有參構造函數:a=" + a);
System.out.println("Parent有參構造函數:b=" + b);
}
//方法
void function(){
System.out.println("Parent function run ......");
}
}

package com.test;

public class Child extends Parent {

int x = 10;
static int y = 11;
//靜態代碼塊
static {
System.out.println("Child靜態代碼塊:y=" + y);
y++;
}
//代碼塊
{
System.out.println("Child代碼塊:x=" + x);
System.out.println("Child代碼塊:y=" + y);
y++;
x++;
}
//構造函數
Child(){
System.out.println("Child無參構造函數:x" + x);
System.out.println("Child無參構造函數:y=" + y);
}
//方法
void function(){
System.out.println("Child function run ......");
}

}

package com.test;

public class testPC {
public static void main(String[] args) {

Child demo = new Child();
demo.function();
System.out.println("............................................................");
/* Child child = new Child();
child.function();*/
}
}


結果:

parent靜態代碼塊:b=11
Child靜態代碼塊:y=11
Parent代碼塊:a=10
Parent代碼塊:b=12
Parent無參構造函數:a=11
Parent無參構造函數:b=13
Child代碼塊:x=10
Child代碼塊:y=12
Child無參構造函數:x11
Child無參構造函數:y=13
Child function run ......
............................................................
Parent代碼塊:a=10
Parent代碼塊:b=13
Parent無參構造函數:a=11
Parent無參構造函數:b=14
Child代碼塊:x=10
Child代碼塊:y=13
Child無參構造函數:x11
Child無參構造函數:y=14
Child function run ......





Java類的加載和對象創建流程的詳細分析