Given a class like the this:
public class Book {
private String title;
private int pages;
private static ArrayList<Book> ArrayBooks = new ArrayList<Book>();
public Book(String titl, int page){
title=titl;
pages=page;
}
}
How can I keep a reference to every Book in the List, in a way that doesn't require any special calls - ie done automatically by the constructor.
Also, the List should have a max size of 20 books; if the user attempts to create the 21st book, he shouldn't be able to.
Can anyone figure out a way to implement it?
To access the current object, you could use the this
reference. So your constructor could look like this:
public Book(String title, int pages) {
this.title = title; // avoid abbreviations like "titl"
this.pages = pages; // or "page" just to avoid same variable names
ArrayBooks.add(this); // add new Book instance into the list
}
To avoid more than 20 entries, you have to check the current amount of entries in the list:
public Book(String title, int pages) {
this.title = title;
this.pages = pages;
(if ArrayBooks.size < 20) {
ArrayBooks.add(this); // add new Book instance into the list
}
}
And I recommend to read the Java naming conventions. So ArrayBooks
should be arrayBooks
.
Edit
To prohibit more than 20 Book
instances, you'll need a factory method that takes care about creating the instances for you:
public static Book create(final String title, final int pages) {
if (ArrayBooks.size() < 20) {
final Book instance = new Book(title, pages);
ArrayBooks.add(instance);
return instance;
}
return null;
}
private Book(String title, int pages) { // "hide" the constructor, so the user can't use this instead of the factory
this.title = title;
this.pages = pages;
}
You could also throw an exception in your constructor, but I personally don't like that. It is up to you, which way you take.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments