更新時間:2022-11-29 11:03:24 來源:動力節點 瀏覽1204次
Java類的初始化是什么?動力節點小編來告訴大家。
順序依次是:
類的靜態部分(靜態代碼塊 + 靜態域(類的static變量))
非靜態部分(構造代碼塊 + 非靜態域)
構造器
class Demo{
Demo(int id){
System.out.println("DEMO "+ id);
}
}
public class InitTest {
Demo d = new Demo(0);
static Demo d1 = new Demo(1);
InitTest(){
System.out.println("InitTest");
}
{
System.out.println("構造代碼塊");
}
static {
System.out.println("靜態代碼塊");
}
static Demo d2 = new Demo(2);
Demo d3 = new Demo(3);
public static void main(String[] args) {
new InitTest();
}
}
/*
DEMO 1
靜態代碼塊
DEMO 2
DEMO 0
構造代碼塊
DEMO 3
InitTest
*/
2.繼承中的初始化順序
父類的靜態部分(靜態代碼塊 + 靜態域(類的static變量))
子類的靜態部分(靜態代碼塊 + 靜態域(類的static變量))
父類的非靜態部分(構造代碼塊 + 非靜態域)
父類的構造器
子類的非靜態部分(構造代碼塊 + 非靜態域)
子類的構造器
class Other{
Other(String str){
System.out.println(str + "調用");
}
}
class Sup{
Other s0 = new Other("父類Others0");
Sup(){
System.out.println("父類的默認構造");
}
Sup(int id){
System.out.println("Sup " + id);
}
static Other s1 = new Other("父類static Others1");
static {
System.out.println("父類的靜態代碼塊");
}
static Other s2 = new Other("父類static Others2");
Other s3 = new Other("父類Others3");
{
System.out.println("父類的構造代碼塊");
}
}
class Sub extends Sup{
Other s0 = new Other("子類Others0");
Sub(){
System.out.println("子類的默認構造");
}
Sub(int id){
System.out.println();
}
static Other s1 = new Other("子類static Others1");
{
System.out.println("子類的構造代碼塊");
}
static {
System.out.println("子類的靜態代碼塊");
}
Other s2 = new Other("子類Others2");
static Other s3 = new Other("子類static Others3");
}
public class InheritInit {
public static void main(String[] args) {
new Sub();
}
}
/*
父類static Others1調用
父類的靜態代碼塊
父類static Others2調用
子類static Others1調用
子類的靜態代碼塊
子類static Others3調用
父類Others0調用
父類Others3調用
父類的構造代碼塊
父類的默認構造
子類Others0調用
子類的構造代碼塊
子類Others2調用
子類的默認構造
*/
以上就是關于“一文了解Java類的初始化”介紹,大家如果想了解更多相關知識,不妨來關注一下本站的Java教程,里面還有更豐富的知識等著大家去學習,希望對大家能夠有所幫助哦。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習