1.什么是構(gòu)造函數(shù)辞居?
構(gòu)造函數(shù)用于初始化對象的狀態(tài)楷怒。與方法類似,構(gòu)造函數(shù)還包含在創(chuàng)建對象時執(zhí)行的語句集合(即指令)瓦灶。
2.我們有Java中的復(fù)制構(gòu)造函數(shù)嗎鸠删?
像C ++一樣,Java也支持拷貝構(gòu)造函數(shù)贼陶。但是刃泡,與C ++不同的是巧娱,如果您不寫自己的Java,則不會創(chuàng)建默認的拷貝構(gòu)造函數(shù)烘贴。
要將一個對象的值復(fù)制到另一個對象中禁添,可以使用:構(gòu)造函數(shù)
將一個對象的值分配給另一個對象
Object類的clone()方法
3.什么是構(gòu)造器鏈接?
構(gòu)造函數(shù)鏈是從一個構(gòu)造函數(shù)調(diào)用另一個構(gòu)造函數(shù)的技術(shù)桨踪。this()用于調(diào)用相同的類構(gòu)造函數(shù)老翘,其中super()用于調(diào)用超類構(gòu)造函數(shù)。
// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
class Temp
{
??? // default constructor 1
??? // default constructor will call another constructor
??? // using this keyword from same class
??? Temp()
??? {
??????? // calls constructor 2
??????? this(5);
??????? System.out.println("The Default constructor");
??? }
??? // parameterized constructor 2
??? Temp(int x)
??? {
??????? // calls constructor 3
??????? this(5, 15);
??????? System.out.println(x);
??? }
??? // parameterized constructor 3
??? Temp(int x, int y)
??? {
??????? System.out.println(x * y);
??? }
??? public static void main(String args[])
??? {
??????? // invokes default constructor first
??????? new Temp();
??? }
}
4.我們可以從超類構(gòu)造函數(shù)中調(diào)用子類構(gòu)造函數(shù)嗎锻离?
不铺峭。在java中沒有辦法從超類構(gòu)造函數(shù)中調(diào)用子類構(gòu)造函數(shù)。
5.如果為構(gòu)造函數(shù)保留返回類型會發(fā)生什么汽纠?
理想情況下卫键,構(gòu)造函數(shù)不能有返回類型。根據(jù)定義疏虫,如果一個方法有一個返回類型永罚,它不是一個構(gòu)造函數(shù)。它將被視為一種常規(guī)方法卧秘。但是呢袱,編譯器會發(fā)出警告,指出該方法具有構(gòu)造函數(shù)名稱翅敌。示例:
class GfG
{
? ? int GfG()
? ? {
? ? ? ? return 0;? ? // Warning for the return type
? ? }
}
6.什么是無參數(shù)構(gòu)造函數(shù)羞福?
不帶參數(shù)的構(gòu)造函數(shù)被稱為no-arg構(gòu)造函數(shù)。java中的默認構(gòu)造函數(shù)始終是一個無參數(shù)構(gòu)造函數(shù)蚯涮。
class GfG
{
? ? public GfG()
? ? {
? ? ? ? //No-arg constructor
? ? }
}
7.無參構(gòu)造函數(shù)與默認構(gòu)造函數(shù)不同的地方治专?
如果一個類不包含構(gòu)造函數(shù)聲明,那么隱式聲明一個沒有形式參數(shù)且沒有throws子句的默認構(gòu)造函數(shù)遭顶。
如果聲明的類是原始類Object张峰,則默認構(gòu)造函數(shù)具有空的主體。否則棒旗,默認構(gòu)造函數(shù)只是簡單地調(diào)用沒有參數(shù)的超類構(gòu)造函數(shù)喘批。
8.什么是私人構(gòu)造函數(shù),它們在哪里使用铣揉?
像任何方法一樣饶深,我們可以為構(gòu)造函數(shù)提供訪問說明符。如果它是私人的逛拱,那么它只能在課堂內(nèi)進行訪問敌厘。
我們使用私有構(gòu)造函數(shù)的主要場景是:內(nèi)部構(gòu)造器鏈接
單件類設(shè)計模式
9.我們什么時候需要構(gòu)造函數(shù)重載?
有時需要用不同的方式初始化一個對象朽合。這可以使用構(gòu)造函數(shù)重載來完成俱两。不同的構(gòu)造函數(shù)可以通過實現(xiàn)不同的代碼行來完成不同的工作饱狂,并根據(jù)傳遞的參數(shù)的類型和數(shù)量來調(diào)用。
根據(jù)情況锋华,在重載構(gòu)造函數(shù)中使用特定數(shù)量的參數(shù)調(diào)用構(gòu)造函數(shù)嗡官。