I am learning java. I am trying to use composite design pattern. I am trying to use following logic. ( Don't laugh I know it is very basic :) )
Item -> interface
Folder -> class
File -&开发者_如何学编程gt; class
In folder class, can I create an arraylist of Item to store files information?
ArrayList<Item> info = ArrayList<Item>();
Or should I use Folder Arraylist?
ArrayList<Folder> info = ArrayList<Folder>();
I don't know if interface can store real data as there is no variable just function definitions.
Thanks for helping a newbie :)
You can do both (with some syntactic correction)
List<Item> info = new ArrayList<Item>();
With regards to this comment:
I don't know if interface can store real data as there is no variable just function definitions.
Interfaces do more than provide function definitions. Most importantly, they define a type. info
, declared as above, is a list of objects of type Item
. Those objects can most certainly store data.
As an example, consider the following:
interface Item { ... }
class Folder implements Item { ... }
Item it = new Folder();
Now, it
refers to an instance of Folder
, which is an Item
.
An interface can't store data. An interface is a Type that you can use as a contract that your Files and Folder classes will implement. Since your Files and Folder classes both implement the Item interface, you can add files and folder objects to the List that accepts the Item type.
List<Item> info = new ArrayList<Item>()
As long as Folder
and File
both implement Item
, this will work fine. Be aware, however, that you will only have access to the properties that are defined in the Item
interface: not those specific to Folder
or specific to File
.
From what you've described, it sounds like a reasonable way to approach the problem, although it's hard to say for sure without knowing more about the use of this data structure.
You certainly can create an ArrayList of Items. It is not a problem that Item, as an interface, doesn't have instance variables. The only Items that can be created, however, are not "just" Items - they will be instances of some class that implements
the Item interface. So, for instance, if Folder and File both implement the Item interface, you can put both Folders and Files into that ArrayList. But the ArrayList would be declared just to hold Items - and, since they implement that interface, both Folders and Files qualify - they are Items.
精彩评论