Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with creating new objects....

Status
Not open for further replies.

Jappen

Technical User
Oct 2, 2002
2
SE
I'm kind of a newbie in Java, so I'm having some problems that hopefully you can solve without problems...

Here's the problem:

public void newbook(String title)
{
Book .... = new Book(); /*where Book is another class*/
}

and were the "...." is, I want the value of title. Have tried for hours, but I can't find any solution.=( Is there anyway I can do this?
 
Hi Jappen,
There is no way to do what you want, and even if there was, it would only affect the variable name of the Book object, not the object itself.
I'm assuming that you want the title to be related to the Book object, and if thats the case, I would pass the title into the Book objects constructor, like so:
Code:
  public void newBook (String title) {
    Book book = new Book (title); 
  }
Changes to the Book object may be needed.

Hope this Helps,
MarsChelios
 
Hi!
Thanks for your reply...

Nowonder I didn't find any solutions then!=)

But if I f.e. want to add 15 new books with this method. And all need a title and a auther, doesn't the new ones "overwrite" the old ones?
If I've added one book, then the name of that object is book, and then I creative another one. Then that objects name is book?!
Or I have missed something? (I probably have...=)
 
If you're going to be creating multiple books, you will need some way to store them. If you know how many books you'll need in advance, an array would be simplest. If you don't know, try a Vector or other Collection object.
Something like this for arrays:
Code:
  Book [] books = new Book [15];
  books [0] = new Book ("Some Java Book");
or, with a Vector:
Code:
  Vector books = new Vector ();
  books.addElement (new Book ("Some Java Book"));
Hope this helps,
MarsChelios
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top