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

5
  • public static void main(TextBook[] args, int x) - is it allowed ? Commented Nov 2, 2015 at 15:50
  • 1
    @Rehman main can be overloaded. Check here. Commented Nov 2, 2015 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 Commented Nov 2, 2015 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. Commented Nov 2, 2015 at 16:05
  • Was there a problem with my answer that caused you to not accept it? Commented Nov 3, 2015 at 14:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.