I'm not sure how to declare and initialize the (empty) array, so that then I can create a method where I can add new titles to the array.
Arrays in java cannot grow or shrink. You pick a size when you make them and that's that. At best, you can take a variable (which points at an object, it isn't the same thing as the object), and then perform this song and dance routine:
- Make a second, new array that is larger or smaller.
- Copy elements from the first array to the newly created array.
- Update the variable to point at the new array.
Which feels like 'resizing' an array but that's not really what you're doing: You are making a new pre-sized array (with a different size) and then just updating your address book, so to speak.
In general, you should not be using arrays in the first place. Use a List<FictionBook>; lists can grow and shrink and have all sorts of useful operations for them.
Other hints:
class FictionBooks is incorrect. You'd want class FictionBook.
- If you want to store fiction books, movies, and newspapers into a single array or list, then this makes no sense unless there's something they have in common. If they have something in common, create a type hierarchy:
abstract class Media {}
class FictionBook extends Media {}
class Newspaper extends Media {}
// and so on
and then you can have a List<Media> media = new ArrayList<>();, and e.g. call media.add(new Newspaper()) and it'll compile fine.
I can tell you: Hey, there's this fruit basket and its filled with fruit!
That sentence makes sense to you, right? So you walk over to the table and there's the basket. It's got an apple, a banana, a pear, an orange... that's fine too, right? Nothing surprising there.
That's what's happening here: Media is like Fruit, and Newspaper is like Banana:
class Banana extends Fruit {}
is you saying in programming terms: There's this concept, called banana. It's like the entry of 'banana' in a encyclopedia. You can't eat it.
Banana banana = new Banana();
This makes an actual banana (you can eat it), it also declares a variable named banana, restricts this variable to be capable of only pointing at bananas (or nothing), and then updates the variable to contain instructions to find the banana.
You could say Fruit fruit = new Banana(); just the same: All bananas are fruit, so whateever you can do with fruit, you can do with a banana. Hence, that's fine.
If you insist on using arrays, the same principle applies:
Media[] library = new Media[10];
library[0] = new Newspaper();
library[1] = new FictionBook();
That's will all compile and run just fine.
Listinstead - or anotherCollectionbutListcomes close to arrays i. e.ArrayListwhich uses an array internally. But you don't have to handle the problem, that the size of an array cannot be changed.