關(guān)于構(gòu)造函數(shù)的Java面試問題

1.什么是構(gòu)造函數(shù)?

構(gòu)造函數(shù)用于初始化對象的狀態(tài)。與方法類似,構(gòu)造函數(shù)還包含在創(chuàng)建對象時執(zhí)行的語句集合(即指令)。

2.我們有Java中的復制構(gòu)造函數(shù)嗎?

像C ++一樣,Java也支持拷貝構(gòu)造函數(shù)。但是,與C ++不同的是,如果您不寫自己的Java,則不會創(chuàng)建默認的拷貝構(gòu)造函數(shù)。

要將一個對象的值復制到另一個對象中,可以使用:構(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ù)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容