JAVA - 对象构造函数不接受参数?

标签 java oop parameters constructor

我最近接触了 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/

相关文章:

c++ - 需要有关类(class)的帮助

oop - 在MVC中, View 应该知道模型吗?

Java通过 protected getter访问私有(private)父类(super class)成员

JavaScript 对象设置/获取参数

java - 如何验证 JTextField?

java - 将请求范围定义为集成测试的原型(prototype)

java - 如何在 JAR 之外但相对于 JAR 加载文件?

objective-c - Objective-C 中的方法名称是相同的。

postgresql - 您如何才能有效地对存储在数据库中的应用程序参数进行版本控制?

java - Netbeans 创建的项目没有 glassfish-web.xml