2

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??

ccc
  • 370
  • 5
  • 19
anony
  • 79
  • 1
  • 2
  • 10
  • `public static void main(TextBook[] args, int x) ` - is it allowed ? – Rahman Nov 02 '15 at 15:50
  • 1
    @Rehman `main` can be overloaded. Check [here](http://stackoverflow.com/questions/3759315/can-we-overload-the-main-method-in-java). – sam Nov 02 '15 at 15:54
  • so are you saying my main is wrong? the int x was supposed to be a single parameter which determines how many number of textbooks the bookshelf could hold – anony Nov 02 '15 at 16:01
  • Step one - create an array that can hold TextBook objects. Correct. Step two - create those TextBook objects. Wrong syntax there; it should simply read `bookShelf[i] = new TextBook()`; assuming that your TextBook class has a constructor going without arguments. – GhostCat Nov 02 '15 at 16:05
  • Was there a problem with my answer that caused you to not accept it? – Kevin Klute Nov 03 '15 at 14:28

1 Answers1

1

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.

Kevin Klute
  • 450
  • 1
  • 4
  • 22