2010-03-16 37 views
6

嗯,也許這是一個愚蠢的問題,但我無法解決這個問題。爲什麼Java找不到我的構造函數?

在我ServiceBrowser類我有這樣一行:

ServiceResolver serviceResolver = new ServiceResolver(ifIndex, serviceName, regType, domain); 

而且編譯器會抱怨它。它說:

cannot find symbol 
symbol : constructor ServiceResolver(int,java.lang.String,java.lang.String,java.lang.String) 

這是奇怪的,因爲我有在ServiceResolver構造:

public void ServiceResolver(int ifIndex, String serviceName, String regType, String domain) { 
     this.ifIndex = ifIndex; 
     this.serviceName = serviceName; 
     this.regType = regType; 
     this.domain = domain; 
    } 

新增: 我從構造函數刪除void和它的作品!爲什麼?從簽名

public ServiceResolver(int ifIndex, String serviceName, String regType, String domain) { 
     this.ifIndex = ifIndex; 
     this.serviceName = serviceName; 
     this.regType = regType; 
     this.domain = domain; 
    } 
+2

'void'用於方法,不用於構造函數。 – BalusC 2010-03-16 14:34:56

+0

@羅曼你是否用不同的賬戶回答你自己的問題? – Bozho 2010-03-16 18:54:32

+0

@波索,另一個羅馬人是另一個人。 – Roman 2010-03-17 09:21:08

回答

9

刪除無效您已經定義了一個方法,而不是一個構造函數。

取出void

5

+0

Bonho,另一位羅馬人是另一個人。我不會從另一個帳戶回答我的問題。 – Roman 2010-03-17 09:22:09

2

這是沒有構造...這是不返回任何內容的簡單方法。絕對沒有!

應該是這樣的:

public ServiceResolver(int ifIndex, String serviceName, String regType, String domain) { 
     this.ifIndex = ifIndex; 
     this.serviceName = serviceName; 
     this.regType = regType; 
     this.domain = domain; 
    } 
0

Java的構造函數沒有對他們簽名的返回類型 - 他們含蓄返回類的一個實例。

0

歡迎大家每次做錯一次。正如Roman指出的,你必須從構造函數的infront中刪除「void」。

構造函數聲明無返回類型 - 這可能看起來很奇怪,因爲你做的事情如x = new X();但你可以認爲它是這樣的:

// what you write... 
public class X 
{ 
    public X(int a) 
    { 
    } 
} 

x = new X(7); 

// what the compiler does - well sort of... good enough for our purposes. 
public class X 
{ 
    // special name that the compiler creates for the constructor 
    public void <init>(int a) 
    { 
    } 
} 

// this next line just allocates the memory 
x = new X(); 

// this line is the constructor 
x.<init>(7); 

一套好的工具來運行發現,這一類的錯誤(和許多其他人)是:

這樣,當你犯了其他常見錯誤(你會的,我們都這樣做:-),你不會爲了尋找解決方案而花費太多精力。

相關問題