我最近接触了 java,目前遇到了一些问题。
我有一个简单的类,它有 2 个字符串作为成员和 1 个构造方法。 这是我的课:
class ErrorMessage{
public void ErrorMessage(String type, String message){
this.type = type;
this.message = message;
}
private String type;
private String message;
如您所见,我的默认构造函数接受 2 个字符串并设置相应的数据成员。
每当我尝试实际调用该构造函数时,我的问题就会出现。 在我的主要功能中,我从 String 和 errorMessage 类的 TreeSet 创建了一个 TreeMap
TreeMap<String, TreeSet<ErrorMessage>> log = new TreeMap<>();
问题是每当我尝试将新的 ErrorMessage 对象添加到我的树状图的给定条目时,我都会收到一个错误消息,指出我的构造函数不接受 2 个字符串。 (查看下图)
只有当我像这样将它留空时,它才会让我这样做:
log.get(projectName).add(new ErrorMessage());
Soo,我想知道我做错了什么,以至于我的编译器无法识别我的构造函数? 这是完整的代码: http://pastebin.com/i76EYmm1
最佳答案
这不是正确的构造函数:
public void ErrorMessage(String type, String message){
this.type = type;
this.message = message;
}
...对于编译器这只是恰好名称与类名相同的方法!
来自文档:
Constructor declarations look like method declarations—except that they use the name of the class and have no return type
正确的构造函数应该是这样的:
public ErrorMessage(String type, String message){
this.type = type;
this.message = message;
}
记住:构造函数中没有返回类型!
关于JAVA - 对象构造函数不接受参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37097372/