簡體   English   中英

可以在類的構造函數中使用“new”來調用Java中的另一個構造函數嗎?

[英]Can “new” be used inside the constructor of the class to call another constructor in Java?

我知道this(...)用於從另一個構造函數調用一個類的構造函數。 但是我們可以使用new的嗎?

為了更清楚這個問題,Line-2是否有效? 如果是(因為編譯器沒有投訴),為什么輸出為null而不是Hello

class Test0 {
    String name;

    public Test0(String str) {
        this.name= str;
    }

    public Test0() {
        //this("Hello");    // Line-1
        new Test0("Hello"){}; // Line-2
    }

    String getName(){
        return name;
    }
}

public class Test{
    public static void main(String ags[]){
        Test0 t = new Test0();
        System.out.println(t.getName());
    }
}

它是有效的,但它在該構造函數中創建一個完全獨立Test0實例(更具體地說是Test0的匿名子類的實例),並且它沒有在任何地方使用。 當前實例仍將字段name設置為null

public Test0() {
    // this creates a different instance in addition to the current instance
    new Test0("Hello"){};
}

請注意,如果使用無參數構造函數調用new運算符,則會出現StackOverflowError

您嘗試做的是通過您注釋掉的代碼完成的:

public Test0()
{
    this("Hello");
}

第2行是有效的聲明。 這就是編譯器沒有顯示任何錯誤的原因。 但是你在那里創建一個匿名對象。 退出構造函數后,它很快就會消失。 因此,該值仍然為null,因為沒有分配給它。

new Test0("Hello"){};

上面的行將創建一個Test0類的匿名實例,並將name值賦給name變量。 但是,由於您沒有引用創建的匿名實例,它將從后續行中消失。 所以你還沒有為調用特定代碼段的實例的name變量賦值。 因此name為null

就像在記憶中一樣

在此輸入圖像描述

因為您創建一個名為“hello”的Test0的新實例,但從不使用它。

public Test() {

    new Test0("hello") // nothing is referencing this new object
}

您只需在另一個構造函數中創建一個對象,但它對第一個構造函數調用創建的實例沒有任何影響。

可以這樣做,但這個new用法的結果將在構造函數的末尾消失。 特別是, t.name將為null

使用this("Hello")

Name是實例變量。 實例變量是特定於對象的。

新的Test0(“你好”); 您正在創建Test0的新實例。

如果您希望t.getName()返回“Hello”[我的意思是獨立於對象的字段值],請將name字段更改為static:

static String name;

您可以通過以下代碼使用new關鍵字來顯示輸出。因為您使用了public Test0(){new Test("Hello){};" 這里{}大括號並不重要。所以當test0()構造函數時......在這個構造函數里面test0(args); 在第一個構造函數中被調用bt你沒有顯示輸出..將會顯示你的“Hello”將顯示..所以只需編輯

`

public test0(String str)
{
 this.name=str;
System.out.println(str);
}`

你會得到你想要的輸出..見下面的代碼..

class test01{
public test01(String str)
{System.out.println(str);
   }
public test01(){

    new test01("Print");
}
}public class Const {
public static void main(String args[])
{test01 t = new test01();

    //System.out.println(t.getName());
    }}

此代碼的輸出將為您提供所需的String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM