Results 1 to 3 of 3
- 01-06-2012, 04:05 PM #1
Member
- Join Date
- Nov 2011
- Posts
- 5
- Rep Power
- 0
HELP!!! How to create an object with parameter problem
public class Book {
String title;
double price;
//Constructor
public Book(String title, double price){
this.title = title;
this.price = price;
}...
public class BookStore {
String name;
List<Book> bookList;/* = new ArrayList<Book>();*/
//Constructor
public BookStore(String name, List<Book> bookList){
this.name = name;
this.bookList = bookList;
}...
public class TestBookStore {
public static void main(String args[]){
Book book = new Book("Java Programming", 200.0);
BookStore bookStore = new BookStore(what should i type here?);
bookStore.displayBooks();
}...
}
BookStore bookStore = new BookStore("ABC BOOK", ?????, ?????);
- 01-06-2012, 04:15 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
Re: HELP!!! How to create an object with parameter problem
Well, you need to provide a List of Books, which would presumably include the Book you just created.
So create a List<Book> and add the book to it, then pass that in.
ETA: Though it does seem odd to me that a BookStore would start with a populated list of books.
I'd have thought the constructor would simply have the store name, and there would be an empty list created.
Then you'd have addBook and addBooks methods to add stuff to it.
- 01-06-2012, 11:10 PM #3
Member
- Join Date
- Jan 2012
- Posts
- 7
- Rep Power
- 0
Re: HELP!!! How to create an object with parameter problem
in this case you should type something like this:
BookStore bookStore = new BookStore("NAME",new LinkedList<Book>()
{
{{
add(new Book("book1",12.22));
add(new Book("book2",12.22));
}}
});
(double braces are a anonymous constructor in anonymous class)
and remember to make BookStore 'static' due to invoking constructor from static method TestBookStore.main
If you want to use comma separated list you can do this
//Constructor
public BookStore(String name, Book ... bookList){
this.name = name;
this.bookList = Arrays.asList(bookList);
}
and then
new BookStore("NAME", new Book("book1",12.22), new Book("book2",12.22));Last edited by czajah; 01-06-2012 at 11:48 PM.
Similar Threads
-
real time example of object as a parameter and copy constructors
By krishanu in forum New To JavaReplies: 1Last Post: 05-25-2011, 09:01 AM -
What is best object to create?
By lam5442 in forum New To JavaReplies: 1Last Post: 02-23-2011, 09:44 PM -
object sending itself as a parameter
By appleLove in forum New To JavaReplies: 3Last Post: 01-07-2011, 04:48 PM -
Create object of unknown class, based on existing object
By Zack in forum New To JavaReplies: 2Last Post: 06-22-2010, 04:29 AM -
create object
By paul21 in forum New To JavaReplies: 4Last Post: 03-07-2010, 07:14 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks