I am a very new beginner at Java and trying to make an array that holds objects created from another class.
To break it down, I have a class called TextBook
, which stores the title of the book, and LibraryClass
, which has a TextBook[] bookShelf
member variable. This member array is where the textbooks will be stored.
So I think what I need to do is:
public class LibraryClass
{
private TextBook[] bookShelf;
public static void main(TextBook[] args, int x) {
TextBook [] bookShelf = new TextBook[x];
for(int i=0;i<bookShelf.length;i++)
{
bookShelf[i] = TextBook[];
}
}
bookShelf[i] = TextBook[];
is where I am stuck. The new textbook objects created will come out like textBook1
, textBook2
, textBook3
and so on. I need to somehow link bookShelf[i]
to textBook1,2,3
etc. but how??
bookShelf[i] = new TextBook();
instead of bookShelf[i] = TextBook[];
assuming your TextBook class had a no args constructor.
This is how you create a new object new
is a necessary keyword for this, and calling TextBook()
will call the constructor of the object.
Every index in the array will have a new TextBook object.
These objects can be accessed with bookShelf[i]
where i
is the index of the object you are trying to access.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.