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

为什么Java找不到我的构造函数?,java,constructor,compilation,Java,Constructor,Compilation,嗯,也许这是个愚蠢的问题,但我无法解决这个问题 在我的ServiceBrowser课程中,我有一行: ServiceResolver serviceResolver = new ServiceResolver(ifIndex, serviceName, regType, domain); 编译器对此抱怨不已。它说: cannot find symbol symbol : constructor ServiceResolver(int,java.lang.String,java.lang.Str

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

在我的
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;
    }

您定义了一个方法,而不是构造函数


删除没有构造函数的
void

。。。这是一个不返回任何内容的简单方法。绝对没有

应该是这样的:

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

Java构造函数的签名上没有返回类型——它们隐式返回类的一个实例。

欢迎大家犯一次错误。正如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);
//你写的东西。。。
公共X类
{
公共X(INTA)
{
}
}
x=新的x(7);
//编译器所做的-很好的排序。。。对我们的目的来说已经足够好了。
公共X类
{
//编译器为构造函数创建的特殊名称
公共空间(INTA)
{
}
}
//下一行只是分配内存
x=新的x();
//这一行是构造函数
x、 (七);
查找此类错误(以及许多其他错误)的一组好工具是:


这样,当你犯下其他常见错误时(你会犯,我们都会犯:-),你就不会为了寻找解决方案而旋转车轮。

void
用于方法,而不是构造函数。@Roman你刚才用不同的帐户回答了你自己的问题吗?@Bozho,不。另一个罗马人是另一个人。Bonho,另一个罗马人是另一个人。我没有从另一个帐户回答我的问题。