Index


Overview


When you have the choice, always declare an interface over a class."

Of course, for "construction" you'll need a class:

List<Integer> nums = new ArrayList<>();


But note even in this common example, on the left side we declare an interface.

Why? Let's look at a couple examples.

Example #1 -- Drawable


Sketch



Method Parameter Using Class Type
public void drawAll1(List<Book> books)  {
	//...
}

We define a method that declares a method parameter List that has element types of Book.

Then we can only send books to this method. We can only draw books... 😢



Method Parameter Using Interface Type
public void drawAll2(List<Drawable> drawables)  {
	//...
}

We change the method header so that the method parameter List now has element types of Drawable.
We only need to change the method header (not any code body).

Now we can send all of our objects to the "draw" method! 👍🏽




Example #2 -- List and ArrayList


Example -- Declaring ArrayList
public void analyze1(
#1
ArrayList<String> list)
{ //Tool that analyzes a list //and prints out a summary report //... } public void testShowDiffs1() { //Test #1 List<String> list = null; ArrayList<String> arrayList = null; LinkedList<String> linkedList = null; SuperFastList<String> superFastList = null; //... //Test #1
#2
this.analyze1(list); this.analyze1(arrayList);
#3
this.analyze1(linkedList);
#4
this.analyze1(superFastList); }




Example -- Declaring List
public String analyze2(
#1
List<String> list)
{ /*Tool that analyzes list1 and list2 and shows report of: Elements only in list1, only in list2, in both */ //... return null; } public void testShowDiffs2() { List<String> list = null; ArrayList<String> arrayList = null; LinkedList<String> linkedList = null; SuperFastList<String> superFastList = null; //... //
#2
Test #2
this.analyze2(list); this.analyze2(arrayList); this.analyze2(linkedList); this.analyze2(superFastList); }





Conclusion


From the examples:


However, note that there will be places we'll use a class: