更新時間:2022-11-29 11:03:24 來源:動力節(jié)點 瀏覽1218次
Java類的初始化是什么?動力節(jié)點小編來告訴大家。
順序依次是:
類的靜態(tài)部分(靜態(tài)代碼塊 + 靜態(tài)域(類的static變量))
非靜態(tài)部分(構(gòu)造代碼塊 + 非靜態(tài)域)
構(gòu)造器
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("構(gòu)造代碼塊");
}
static {
System.out.println("靜態(tài)代碼塊");
}
static Demo d2 = new Demo(2);
Demo d3 = new Demo(3);
public static void main(String[] args) {
new InitTest();
}
}
/*
DEMO 1
靜態(tài)代碼塊
DEMO 2
DEMO 0
構(gòu)造代碼塊
DEMO 3
InitTest
*/
2.繼承中的初始化順序
父類的靜態(tài)部分(靜態(tài)代碼塊 + 靜態(tài)域(類的static變量))
子類的靜態(tài)部分(靜態(tài)代碼塊 + 靜態(tài)域(類的static變量))
父類的非靜態(tài)部分(構(gòu)造代碼塊 + 非靜態(tài)域)
父類的構(gòu)造器
子類的非靜態(tài)部分(構(gòu)造代碼塊 + 非靜態(tài)域)
子類的構(gòu)造器
class Other{
Other(String str){
System.out.println(str + "調(diào)用");
}
}
class Sup{
Other s0 = new Other("父類Others0");
Sup(){
System.out.println("父類的默認(rèn)構(gòu)造");
}
Sup(int id){
System.out.println("Sup " + id);
}
static Other s1 = new Other("父類static Others1");
static {
System.out.println("父類的靜態(tài)代碼塊");
}
static Other s2 = new Other("父類static Others2");
Other s3 = new Other("父類Others3");
{
System.out.println("父類的構(gòu)造代碼塊");
}
}
class Sub extends Sup{
Other s0 = new Other("子類Others0");
Sub(){
System.out.println("子類的默認(rèn)構(gòu)造");
}
Sub(int id){
System.out.println();
}
static Other s1 = new Other("子類static Others1");
{
System.out.println("子類的構(gòu)造代碼塊");
}
static {
System.out.println("子類的靜態(tài)代碼塊");
}
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調(diào)用
父類的靜態(tài)代碼塊
父類static Others2調(diào)用
子類static Others1調(diào)用
子類的靜態(tài)代碼塊
子類static Others3調(diào)用
父類Others0調(diào)用
父類Others3調(diào)用
父類的構(gòu)造代碼塊
父類的默認(rèn)構(gòu)造
子類Others0調(diào)用
子類的構(gòu)造代碼塊
子類Others2調(diào)用
子類的默認(rèn)構(gòu)造
*/
以上就是關(guān)于“一文了解Java類的初始化”介紹,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下本站的Java教程,里面還有更豐富的知識等著大家去學(xué)習(xí),希望對大家能夠有所幫助哦。
初級 202925
初級 203221
初級 202629
初級 203743