Why use interface as a reference type

In the case (A) of method parameters, I do understand the idea of using interface as a type, for instance:

interface Digestible {
    int getDigestingTime();

void eat(Digestible compound){

class Food implements Digestible {...}
class Bevrage implements Digestible {...}
class Cereal extends Food {...}
class Milk extends Bevrage {...}
class Sand {...}
class Seawater {...}

Here I can simplify type checking using polymorphism and operate only on desired type of object and also use relevant method provided by the interface, in this case my Person object will eat only object implementing Digestible interface and will not end up in a Hospital object.

But on the other case (B), where constructing object and referencing to an interface, for example within line:

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

Or via constructor:

public class Stack {
    private final List values;
    public Stack() {
        values = new LinkedList();

Developers say this allow as to change the object type to the interface reference in the future if needed. But in the second case (Stack), which I took from a book[Listing 8-22], this will not take place (as the values reference is of a final type). And in the first ArrayList case, if I want for example to use ((ArrayList)list).trimToSize(), I will have to cast- and that goes for every method on an object being referenced by an interface that is not part of the interface. That is ugly.

I see case (B) everywhere, being some kind of an Object Oriented conversion. Should I be following it, or did I just misunderstood the proper use of case (B)? What are the proper use cases for case (B)?

Source: oop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.