Constructing a class from a different class
I have two class: Library and Book.
I want to construct a Book class by calling its class constructor from the Library class. How can i do this? My code doesn't work (Error: Cannot find symbol - Constructor Book() )
Code:
public void createBook()
{
Book newBook;
newBook = new Book(); //Error line
}
Here is the book constructor:
Code:
public Book(String BookAuthor, String BookTitle, String BookCost, String NumberOfPages, String BookGenre, int bookEnjoyability)
{
//Initialise variables
this.BookAuthor = BookAuthor;
this.BookTitle = BookTitle;
this.BookCost = BookCost;
this.NumberOfPages = NumberOfPages;
this.BookGenre = BookGenre;
this.bookEnjoyability = bookEnjoyability;
}
Re: Constructing a class from a different class
You don't have the correct constructor:
You specify this:
public Book(String BookAuthor, String BookTitle, String BookCost, String NumberOfPages, String BookGenre, int bookEnjoyability)
But your calling a constructor that looks like this:
public Book()
Specify all the parameters and it should work:
Book b = new Book("author","title","cost","pages","genre","enjoyment");
I would also recommend making cost and pages ints.
Re: Constructing a class from a different class
In java a default constructor is automatically created, if you don't supply your own. Once you add your own constructor then the default one is not created.
Re: Constructing a class from a different class
Quote:
Originally Posted by System_Error
I would also recommend making cost and pages ints.
Thanks for your answer, i cant change the types of these variables as the specification for my assignment says they have to be string for some reason.
Re: Constructing a class from a different class
Quote:
Originally Posted by System_Error
I would also recommend making cost and pages ints.
As long as no calculations are being done on cost and pages then a string would be fine. Although you would want cost to be double, not int anyway.
Re: Constructing a class from a different class
Quote:
Originally Posted by RyanEllis
As long as no calculations are being done on cost and pages then a string would be fine. Although you would want cost to be double, not int anyway.
I disagree. The inexactness of floating point values makes them unsuitable for monetary calculations. You should use scaled ints or even longs. (That is, establish a convention that says that the int now stands for cents, or if you need the precision, hundredths of cents.)