2010-03-16 43 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); 

一套好的工具来运行发现,这一类的错误(和许多其他人)是:

这样,当你犯了其他常见错误(你会的,我们都这样做:-),你不会为了寻找解决方案而花费太多精力。

相关问题