[英]How can I call parameterized constructor of default type from a parameterized constructor of type public which is in another class?
[英]Can I call default constructor from parameterized constructor inside public class in java?
我想從公共java類中的參數化構造函數調用默認構造函數。
我能實現嗎?
使用this();
在參數化構造函數的第一行中,它將調用您的默認構造函數。 確保你有默認的構造函數,因為如果你聲明一個參數化的構造函數,編譯器就不會提供一個構造函數。
對於Java:您可能意味着沒有參數的構造函數。 如果是這樣,您可以使用以下代碼:
public class MyClass {
// no params constructor
public MyClass() {
...
}
// parametrized constructor
public MyClass(int p1, String p2) {
this();
}
}
希望這可以幫助
是的你可以
public YourClass() {
public YourClass() { super();}
public YourClass(int x) { this();}
}
如果你有相同的參數構造函數。 這不行
public YourClass() {
public YourClass(int x, int y) { this(); } // compiler error here
public YourClass(int x) { super(); }
}
注意: super()調用超級構造函數(在本例中為類Object,因為MyClass隱式擴展Object而類Object具有無arg構造函數),它匹配相同數量的參數。
this()調用當前類的構造函數,該構造函數匹配相同數量的參數。
在Java中,默認構造函數是編譯器隱式提供的無參數構造函數。 如果您引入任何帶參數的構造函數,編譯器將不會提供一個。
在這種情況下,您必須顯式定義無參數構造函數(順便說一下,它不是默認構造函數,因為它不是由編譯器提供的),例如public MyClass() { }
。
你可以從其他構造函數中調用它作為this();
,它必須是構造函數中調用它的第一個語句。
您可以使用new運算符調用默認構造函數(如下所示:new Test();)或this();. 只是Test()是禁止的,因為它不是類的方法。
package org.gpowork.test;
public class Test {
private String field;
private Long time = 0L;
public Test(){
this.time = System.currentTimeMillis();
System.out.println("Default constructor. "+this.time);
}
public Test(String field){
this();
Test instance = new Test();
this.field = field;
}
public static void main(String[] args){
System.out.println("start...");
Test t1 = new Test();
System.out.println("-------");
Test t2 = new Test("field1");
}
}
一旦創建了帶參數的構造函數,就無法調用默認構造函數。 您必須自己創建無參數構造函數,以便從參數化構造函數進行調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.