簡體   English   中英

傳遞null時選擇哪個構造函數?

[英]Which constructor is chosen when passing null?

在下面的示例中,我有2個構造函數:一個使用String,另一個使用自定義對象。 在此自定義對象上,存在一個返回String的方法“getId()”。

public class ConstructorTest {
 private String property;

 public ConstructorTest(AnObject property) {
  this.property = property.getId();
 }

 public ConstructorTest(String property) {
  this.property = property;
 }

 public String getQueryString() {
  return "IN_FOLDER('" + property + "')";
 }
}

如果我將null傳遞給構造函數,選擇哪個構造函數,為什么? 在我的測試中,選擇了String構造函數,但我不知道是否總是這樣,為什么。

我希望有人可以為我提供一些見解。

提前致謝。

通過做這個:

ConstructorTest test = new ConstructorTest(null);

編譯器會抱怨說:

構造函數ConstructorTest(AnObject)不明確。

JVM無法選擇要調用的構造函數,因為它無法識別與構造函數匹配的類型(請參閱: 15.12.2.5選擇最具體的方法 )。

您可以通過類型化參數來調用特定的構造函數,例如:

ConstructorTest test = new ConstructorTest((String)null);

要么

ConstructorTest test = new ConstructorTest((AnObject)null);

更新:感謝@OneWorld,可以在此處訪問相關鏈接(撰寫本文時的最新信息)。

編譯器將生成錯誤。

Java使用它可以根據參數找到的最具體的構造函數。
PS:如果添加構造函數(InputStream),編譯器會因為模糊而拋出錯誤 - 它無法知道更具體的內容:String或InputStream,因為它們位於不同的類層次結構中。

暫無
暫無

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

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