A very small problem I am having. Here is an example:

A class representing a book

public class Book
{
   private String title, author;
   
   //Constructor for book
   public Book (String name, String writer)
   {
      title = name;
      author = writer;
   }

Another class called Bookshelf representing a collection of books

public class  Bookshelf
{
   private Book[] shelf;
   int number;
   
   //Constructor for Bookshelf
   public Bookshelf ()
   {
      shelf = new Book[10];
      number = 0;
   }

Main method:

public class Bookstore
{
   public static void main (String[] args)
   {
      Bookshelf cases = new Bookshelf (); //<-how to retrieve the array inside bookshelf 
      
      System.out.println ("This is: " + Bookstore.somemethod (REALPARAM); //<--
   }
   
   //Static method
   public static void somemethod (PARAMETER)  //<--Array in bookshelf class as PARAMETER
   {
      //some code
   }
}

So as you can see above, I have a static method called somemethod that is designed to accept the array present inside the Bookshelf class (Bookshelf constructor) as its parameter. How should I do this?? What should I put in the field PARAMETER as well as REALPARAM so that I can accomplish this??

Any form of help is greatly appreciated. I have researched online the whole day yesterday and also today. Thanks a lot.

Recommended Answers

All 4 Replies

If I understand correctly, you simply need to create getters and setters for each of your value objects (Book, BookShelf). You can certainly create a constructor that takes an array of Book objects:

public class BookShelf(String[] books) {
...
}

You would be much better off using an ArrayList instead of a primitive array to hold your books in BookShelf, likewise for the BookStore. This way you're not limited to the number of books or bookshelves. I might create a method in BookShelf such as

public void addBooks(List<Book> books) {
...
}

or to add one book,

public void addBook(Book book) {
...
}

Hope that gets you going in the right direction.

Inside Bookshelf you could have a method that returns the 'shelf' array. If you merely want to print the elements of 'shelf' then you could override toString method in Bookshelf. That way when you need to print the elements, you would only need to call toString method after creating an object of Bookshelf.

Hope this helps.

Thank you guys, I will keep you updated if I still have problems

if solved, I will mark this as solved...Thank you...Thank you

Solved!!! Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.