【问题标题】:Java Error: The constructor is undefined (2)Java 错误:构造函数未定义 (2)
【发布时间】:2021-12-14 10:13:32
【问题描述】:

问题:我的重载构造函数是未定义的,即使我在做正确的事情(我认为是这样?)。

源代码:

class Book { 
    String section;
    float subject2;
    char section2, author;
    int subject, author2, year;

Book(String section, int subject, char author, int author2, int year) { 
    this.section = section;
    this.subject = subject;
    this.author = author;
    this.author2 = author2;
    this.year = year;
}
Book(char section2, float subject2, char author, int author2, int year) {
    this.section2 = section2;
    this.subject2 = subject2;
    this.author = author;
    this.author2 = author2;
    this.year = year;
}
void displayData() {
    System.out.println(section + subject + " ." + author + author2 + " " + year);
}
void displayData2() {
    System.out.println(section2 + subject2 + " ." + author + author2 + " " + year);
}}
public class TestBook {
  public static void main(String[] args) {
    Book book1 = new Book("LB", 2395, "C", 65, 1991);
    Book book2 = new Book("E", 185.86, "P", 277, 2010);
    book1.displayData();
    book2.displayData2();
    s.close();  
}}

如果打扰了,敬请原谅。感谢您的帮助!

【问题讨论】:

  • "C" 是 String ,'C' 是 char 。
  • 哦,我没注意到,不过还是谢谢你。 “小帮助带来大不同。”
  • 我认为这实际上只是“扔掉练习代码”,但仍然:在您的代码中使用有意义的名称,尤其是对于您的类的字段。你看,section vs section2,那是什么意思?换句话说:在写代码的时候,也要练习“如何想出好名字”的部分。
  • 不想变得粗鲁,但是,先生,我仍然是一名学习者。我没有参与过我也必须担心我的命名约定的部分。但是,我对您所说的“有意义”的含义有些感兴趣。已经在该领域具有专业知识的人可以提出什么样的名字?

标签: java oop constructor


【解决方案1】:

当你打电话时:

Book book2 = new Book("E", 185.86, "P", 277, 2010);

如果要使用 char 调用第二个构造函数,请将“E”更改为“E”,否则“E”是 String 对象。字段author 也一样(将“P”更改为“P”)

顺便说一句,您可以覆盖toString()方法,而不是创建displayData()方法:

@Override
public String toString() {
    return "your string with information";
}

所以你可以调用这个方法:

System.out.println(book.toString());
System.out.println(book); // The same thing ! It will call the toString() method

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多