为什么Java找不到我的构造函数?

6

也许这是一个愚蠢的问题,但我无法解决这个问题。

在我的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,现在它能正常工作了!为什么呢?


2
void 应该用于方法,而不是构造函数。 - BalusC
@Roman 你刚才是用另一个账号回答了自己的问题吗? - Bozho
@Bozho,不,另一个罗马人是另一个人。 - Roman
5个回答

9

从签名中删除void

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

5
你定义的是一个方法,而不是构造函数。
去掉 void

Bonho,另一个罗马人是另一个人。我不会从另一个账户回答我的问题。 - Roman

2

这不是构造函数...它只是一个返回空的简单方法,绝对什么都不返回!

应该是这样的:

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

0

欢迎来到每个人都会犯的错误。正如Roman所指出的那样,您必须从构造函数前面删除"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);

寻找此类错误(以及许多其他错误)的好工具集包括:

这样,当您犯其他常见错误时(您会犯错的,我们都会犯错:-),您就不必花费太多时间寻找解决方案。


0
Java构造函数在其签名中没有返回类型 - 它们隐式地返回类的实例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接