构造函数未定义

时间:2015-07-23 19:06:04

标签: java constructor

我的任务的问题是:

创建一个名为Book.java的java文件,该文件将包含描述Book的信息。所需信息是:

a)作者

b)标题

c)出版商

d)出版年份

e)页数

为每条信息使用适当的数据类型。 该类将需要每个变量的构造函数,getter和setter方法,以及一个打印Book的描述的toString方法。

我继续收到错误消息,指出未定义构造函数书。 有想法该怎么解决这个吗?

    class Book {

      String author;
      String title;
      String publisher;
      int year;
      int pages;
    /** The following methods are the Getters for 
      * Author
      * title 
      * number of pages
      * year of publication 
    */
    public String getTitle() 
    {
      return title;
    }

    public String getAuthor()
    {
      return author;
    }

    public int getPages()
    {
      return pages;

    }
    public int getYear() 
    {
      return year;
    }

    //:::::::::::::::::::::::::::::::::::::::::::::::
    /**the following Methods are Setters for 
      * Author 
      * title 
      * numer of pages 
      * year of publication
    */
    public void setTitle(String title)
     {
      this.title = title;

     }
    public void setAuthor(String author)
    {
      this.author = author;
    }

    public void setPages(int pages)
    {
      this.pages= pages;
    }
    public void setYear(int year) 
    { 
      this.year=year;

    }
    /*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
     * Constructors for:
     * Author 
     * Title 
     * Pages 
     * Year 
     * prama@ a, t, p, y
     * */
    public Book (String a, String t, int p, int y) {
      author=a; 
      title=t; 
      pages =p; 
      year = y; 


    }
    public String toString (String a, String t, int p, int y){
        String b = title + "\nAuthor: " + author + "\nNumber of Pages: " +          pages+"/nYear of publication"
          +year;
        return b;
    }

    public void main (String  [] args) {

     Book b = new Book ("The Gunslinger", "Stephen King", "224", "1982") ;//error here
        System.out.println (b);

    }
}

2 个答案:

答案 0 :(得分:5)

"224"String。构造函数需要第{和第四个参数的int个参数:

Book b = new Book ("The Gunslinger", "Stephen King", 224, 1982);

此外,覆盖Object#toString()方法不得包含任何参数:

public String toString () {
    String b = title + "\nAuthor: " + author + "\nNumber of Pages: " +          pages+"/nYear of publication"
      +year;
    return b;
}

答案 1 :(得分:2)

请致电

Book b = new Book ("The Gunslinger", "Stephen King", "224", "1982") ;

Book b = new Book ("The Gunslinger", "Stephen King",224,1982) ;

有构造函数:

Book(String,String,int,int)

Book(String,String,String,String)