Isn't it possible to have something like this in the item class or film class so that when a film object is created it automatically adds it self to the array list? is that possible at all?
library.addItem(this film) (pseudo)
because im using bluej and it doesn't require main methods. its supposed to be for beginners...
If you pass the constructor the arraylist as a parameter, you could add it easily, yes.
But it is bad practice to do something like that. If your arraylist is in one class, your methods from another class should simply return data to enter into the arraylist.
Alternatively you could send each method the arraylist as a parameter and then set the arraylist to the return value of the method.
I'm just looking at your code again, and I am wondering why you would want to do it that way. Could you explain what you're attempting to achieve?
You specifically have a method in your Library class for addItem, which adds it to the arraylist, so why would you want that private variable to be accessible from the other classes?
because at the moment on bluej, I create a Library object then I create a Book object and then I call the addItem() to add that book object so I was wondering if it'd be possible to have the last done automatically.
By the way in bluej to create an object, you right click the class from a class diagram and you click 'create new...' so the creation of objects and method calls are done with the mouse no by code.
I'm not sure how bluej works, but why don't you call the addItem and create the book object at the same time(like my above example), instead of doing each one separately?
The only way I can think of achieving what you want is using a singleton design pattern. That way you could declare an instance of your Library class in each method and append the arraylist, but it seems like an ugly way to accomplish it.
Using the singleton method, you would need to create your object, and then call methods to append the array. One benefit would be that you don't need to instantiate the class in your main method.
So to achieve that, you would need to modify your library class to include the below code. Notice that the constructor is changed to protected. The rest is to ensure there is only one instance of the library.
Code:
private static Library instance = null;
protected Library() {
al = new ArrayList<item>();
}
public static Library getInstance() {
if(instance == null) {
instance = new Library();
}
return instance;
}
Then, in each of your methods, you would need to have something like
Code:
Library library = new Library();
library.addItem(this);
In your particular case, it would go in the constructor.
Well, BlueJ is a really cool OO IDE. You design your classes and instead of having code control class instantiation and method calling you can do it yourself.
Anyone trying to learn Object Oriented should definitely use it.
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson My Blog