Why can't Java find my constructor?

Well, maybe this is a stupid question, but I cannot solve this problem.

In my ServiceBrowser class, I have this line:

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

And the compiler complains about it. It says:

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

This is strange because I have a constructor in ServiceResolver:

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

ADDED: I removed void from the constructor and it works! What for?

+6
java constructor compilation
source share
5 answers

remove void from signature

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

You defined a method, not a constructor.

Remove void

+5
source share

This is not a constructor ... it is a simple method that returns nothing. Absolutely nothing!

Must be:

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

Java constructors do not have return types in their signature β€” they implicitly return an instance of the class.

0
source share

Welcome to the mistake you make every time. As Roman points out, you must remove the "void" from the infront of the constructor.

Constructors do not declare a return type - which may seem strange since you are doing things like x = new X (); but you can take it as follows:

 // 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); 

A good set of tools to find such an error (and many others):

Thus, when you make other common mistakes (you will, we all do :-), you won’t spin your wheels so hard to find a solution.

0
source share

All Articles