实例构造与结构构造(Java/C#)

本文解析了实例构造函数与类型构造函数的区别及使用场景,并通过.NET与Java的对比展示了不同语言中构造函数的调用顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

所谓实例构造就是指通常的构造函数带参数的和不带参数的,其中不带参数的构造函数又叫做默认构造函数。而类型构造函数又可称为静态构造函数。例如:

publicclassCustomer...{
publicCustomer()...{...}//instanceconstructor,default
publicCustomer(Typetype)...{...}//instanceconstructorwithargument
staticCustomer()...{...}//typeconstructor
}
其中public Customer(),public Customer(Type type),为实例构造函数,static Customer为类型构造函数,当实例化一个这样的类的时候如:Customer customer = new Customer([Type type])时,CLR首先会调用类型构造函数,然后是实例构造函数。下面看个例子:
publicclassCustomer:Base...{
publicCustomer()...{
System.Console.WriteLine(
"Customerinstanceconstructorwasinvoked.");
}

staticCustomer()...{
System.Console.WriteLine(
"Customertypeconstructorwasinvoked.");
}

}

publicclassBase...{
publicBase()...{
System.Console.WriteLine(
"Baseinstanceconstructorwasinvoked.");
}

staticBase()...{
System.Conole.WriteLine(
"Basetypeconstructorwasinvoked.");
}

}

到创建Customer对象时候,customer = new Customer();时候有如下输出:

Customer type constructor was invoked.

Base type constructor was invoked.

Base instance was invoked.

Customer instance was invoked.

而在Java中却不一样,看下面的例子:

packagemf;
publicclassBase...{
publicBase()...{
System.out.println(
"Baseinstanceconstructorwasinvoked.");
}

static...{
System.out.println(
"Basetypeconstructorwasinvoked.");
}

}

publicclassCustomerextendsBase...{
publicCustomer()...{
System.out.println(
"Customerinstanceconstructorwasinvoked.");
}

static...{
System.out.println(
"Customertypeconstructorwasinvoked.");
}

}

publicclassTest...{
publicstaticvoidmain(String[]args)...{
Customercustomer
=newCustomer();
}


}

其输出结果为:

Base type constructor was invoked.
Customer type constructor was invoked.
Base instance constructor was invoked.
Customer instance constructor was invoked.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值