Kobek Kobek - 6 months ago 10
Java Question

JAVA - Object constructor does not accept parameters?

I recently got into java, and I am currently running into a bit of a problem.

I have a simple class, that has 2 strings as members and 1 constructor method.
Here is my class :

class ErrorMessage{
public void ErrorMessage(String type, String message){
this.type = type;
this.message = message;
}

private String type;
private String message;


}

As you can see my default constructor takes in 2 strings and sets the corresponding data members.

My problem occurs whenever I try to actually call that constructor.
In my main function I have created a TreeMap out of a String and a TreeSet of my errorMessage class

TreeMap<String, TreeSet<ErrorMessage>> log = new TreeMap<>();


The problem is whenever I try to add new ErrorMessage objects to a given entry of my treemap, I get an error that my constructor does not accept 2 strings. (Check picture below)



It only lets me do it if I leave it empty like so:

log.get(projectName).add(new ErrorMessage());


Soo, I was wondering what I am doing wrong, so that my compiler does not recognize my constructor?
Here is the full code :
http://pastebin.com/i76EYmm1

Answer

This is not correct constructor:

public void ErrorMessage(String type, String message){
    this.type = type;
    this.message = message;
}

... for compiler this is just method that happens to have name same as class name!

From docs:

Constructor declarations look like method declarations—except that they use the name of the class and have no return type

Correct constructor should look like this:

public ErrorMessage(String type, String message){
    this.type = type;
    this.message = message;
}

Remember: No return type in constructors!

Comments