Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store interface in array list java

Tags:

java

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 -> 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 :)

like image 467
user238384 Avatar asked Mar 13 '10 23:03

user238384


1 Answers

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.

like image 58
polygenelubricants Avatar answered Oct 05 '22 22:10

polygenelubricants