Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+16 votes

On slide 19 titled "Subtype Polymorphism," it provides examples of Java code:

List myList = new ArrayList();

I'm curious about the functionality or why someone would want to do this in java code. Why wouldn't they set up the variable "myList" as an ArrayList (rather than List).

asked in CSC305 Fall 2023 by (1 point)

1 Answer

+7 votes

If you aren't using any features that are specific to ArrayLists (or LinkedLists), it's considered better coding style to declare a type as the most general type that you are using the features of.

But why? Here are a few reasons:

1) the code is more readable because people reading your code just need to know it's a list, and not worry about whether it is implemented (under the hood) using an array or a linked list. Those are implementation details that probably don't matter much to this software project.

2) the code is more extensible. Suppose that later someone comes up with an even more efficient SuperList class that also implements the List interface. We can take advantage of it by just changing our code (in ONE place) to:

List myList = new SuperList();

We don't have to change it all throughout the program.

3) It's more reusable. If when declaring a method, you write:

void doSomething(ArrayList paramList) { ... }

then your method will only be callable by client code that is using an ArrayList. If they are using a LinkedList instead, they can't run this method! But if you declare your method as:

void doSomething(List paramList) { ... }

Then other client code can call your method regardless of what type of List they are using!

answered by (508 points)