Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming to interface [duplicate]

Tags:

java

interface

From my understanding, you program to an interface rather than a concrete class to restrict yourself from using methods that aren't part of the interface. This helps in the case you want to change the implementation of said interface later on. (Flexibility) i.e.

    List myList = new ArrayList(); // programming to the List interface

instead of

    ArrayList myList = new ArrayList(); // this is bad

Is the reason you can't access methods in ArrayList such as trimToSize(), that aren't part of the List interface, simply because they're not defined in List? Is it similar to as if a class had a public global variable but no method to access it?

Also, if you do decide to change

    List myList = new ArrayList();
    //into
    List myList = new LinkedList();

Would the only reason you would make such a change be for the performance (I see no other reason)? Since in both cases you'd only be able to access the List defined methods, excluding the concrete implementation's extra functionalities.

like image 759
CheeseBites Avatar asked Oct 30 '22 11:10

CheeseBites


1 Answers

People use interface to hide details of details of implementation. For example, I want to write a function that returns size of a collection - it can be a list, an array, a map, anything at all, I don't care. I'll use a pseudo-code, it's not relevant to Java:

int length (Collection c) {
  return c.size();
}

Otherwise, I have to implement 'map_length, list_length' and dozens of other methods. And this will blow up your code dramatically.

Another common example - data bases. There quite a lot of them with different API, request languages, performance, etc. I don't know ahead, which one prefer to use in your application. So you can create generic data base interface and use it as 'a placeholder' around your code. While you hide exact DBs behind an interface, you can switch between various DBs without any issues.

I would recommend you reading further on inheritance and patterns.

like image 150
CaptainTrunky Avatar answered Nov 03 '22 00:11

CaptainTrunky