Reputation: 79
I need to create an Array with objects from another class but the other class use objects of another class in the constructors too... I will try to explain better:
public class BookStore
{
private String storeName; //e.g. "Jason's New Books"
private Book[] inventory; // Array of Book objects
public BookStore()
{
inventory = new Book[100];
inventory[3] = new Book("James Joyce", 2013, "ULYSSES");
}
I need to create this Book Array but I can't figure out how to put the parameters, because in the Book class the constructor is like this:
public Book(Author author, Date published, String title)
As you can see, this constructor uses objects from another class to initiate, and the other class the constructors are like this:
public Date()
and
public Author()
When I try to compile the BookStore class I get the following error:
"incompatible types: java.lang.String cannot be converted to Author"
Upvotes: 1
Views: 93
Reputation: 17132
Use this:
import java.util.Date;
inventory[index] = new Book(
new Author("Author name"),
new Date(115, 11, 10), // The 10th of December, 2015
"book title"
);
Considering that the Author
class has defined such a constructor:
public class Author {
private String name;
// Other member variables
public Author(String name) {
this.name = name;
}
// Other methods
}
Upvotes: 5
Reputation: 21490
The answer from @Sparta has one problem: the month number in java.util.Date is zero-based (January is 0, February is 1, etc) and wraps around, and the year is 1900-based, so new Date(2015, 12, 10)
is not the "10th of December, 2015" but "10th of January 3916"
Sorry, would have liked to comment on your answer but I do not yet have enough reputation...
Upvotes: 1
Reputation: 116
Since your Book class constructer Book(Author author, Date published, String title)
accepts 3 parameters as following
And you are using String, so its throughing that error
Hence, instead of using
inventory[3] = new Book("James Joyce", 2013, "ULYSSES");
Use
Author objAuthor = new Author();
Date objDate = new Date();
inventory[3] = new Book(objAuthor, objDate, "ULYSSES");
Upvotes: 1
Reputation: 18072
You're almost there, you just need to create an instance of each object:
private Book[] inventory; // Array of Book objects
public BookStore()
{
inventory = new Book[100];
inventory[3] = new Book(new Author(), new Date(), "title");
You could alternatively do something like:
Author author = new Author();
Date date = new Date();
inventory[3] = new Book(author, title, "title");
You will need to pass in the required parameters for each object to match your constructor
Upvotes: 1
Reputation: 393846
If you only have parameterless constructors in the Date
and Author
classes, you'll have to create the instances using multiple statements :
Author author = new Author();
author.setName("James Joyce"); // assuming such a method exists
Date date = new Date();
date.setYear(2013); // assuming such a method exists
inventory[3] = new Book(author, date, "ULYSSES");
Upvotes: 2