2013-10-31 82 views
2

我在源文件中看到以下代碼。這是一個構造函數,但我不明白代碼this(null)在這裏意味着什麼。Java(null)是什麼意思?

public DefaultFurnitureCatalog() { 
    this((File)null); 
} 

任何人都可以幫忙嗎?

回答

6

它要求有一個File參數

+6

通常,如果有人投了'null'的類型,如'File',這是因爲有采取單一的非基本參數等多個構造消歧是必需的。 –

0

它意味着調用一個重載的構造函數這需要某種類型的Object,但你不及格的對象對同一個對象的另一個構造函數,而是一個普通的null

0

它使用null參數調用構造函數public DefaultFurnitureCatalog(File f)。 爲什麼?因此public DefaultFurnitureCatalog()將使用與public DefaultFurnitureCatalog(File f)相同的邏輯。

0

從Java文檔Using the this Keyword

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.

所以它會調用它有一個單一的文件參數同一對象的另一個構造函數。就像下面:

public class DefaultFurnitureCatalog{  
    public DefaultFurnitureCatalog() { 
     this((File)null); // this will call below constructor 
    } 

    public DefaultFurnitureCatalog(File file) { 
     // doing something 
    } 
} 
0

條件1:

從甲骨文的Java教程:

從構造函數中,您還可以使用this關鍵字來調用另一個構造在同一個班級。這樣做被稱爲顯式構造函數調用

如果存在,另一個構造的調用必須在構造的第一行。

因此,在顯式構造函數調用之前,您無法創建指向null的File引用。

例如:下面的代碼拋出編譯錯誤:調用這必須是第一條語句構造

公共類你好{

public Hello() { 
    File file = null; 
    this(file); 
    System.out.println("hello - 1"); 
} 
public Hello(File file) { 
    System.out.println("hello - 2"); 
} 

public Hello(String str) { 
    System.out.println("hello - 3"); 
} 

public static void main(String[] args) { 
    Hello h = new Hello(); 
} 

}

條件2:

檢查代碼,你有多個構造函數接受一個Object類型的輸入參數(一般情況下)嗎?

例如,下面的代碼拋出編譯錯誤:參考你好是不明確的,既構造你好(文件)在您好,構造你好(字符串)在你好比賽

公共類你好{

public Hello() { 
    this(null); 
    System.out.println("hello - 1"); 
} 
public Hello(File file) { 
    System.out.println("hello - 2"); 
} 

public Hello(String str) { 
    System.out.println("hello - 3"); 
} 

public static void main(String[] args) { 
    Hello h = new Hello(); 
} 

}

爲了避免歧義,類型轉換,如下空:

公共類你好{

public Hello() { 
    this((File)null); 
    System.out.println("hello - 1"); 
} 
public Hello(File file) { 
    System.out.println("hello - 2"); 
} 

public Hello(String str) { 
    System.out.println("hello - 3"); 
} 

public static void main(String[] args) { 
    Hello h = new Hello(); 
} 

}

希望,這有助於