What is the advantage of declaring a reference variable as an interface type in JAVA?

I was reading this PowerPoint presentation when I came across this:

When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referenced. This is one of the key features of interfaces. The method to be executed is dynamically viewed at runtime, allowing you to create classes later in the code that calls methods on them.

Can anyone explain this concept to me? I've mentioned several sites and a book and I still don't understand how this concept works. We know from the above line that it is calling the correct version of the method. How does it work and when should I overlay an object on an interface type.

+3


source to share


1 answer


Let's give an example using an interface List

. Its two implementations: ArrayList

and LinkedList

. The first one recovers a random element very quickly (for example, the sixth one using the method get(6)

), but slowly adds and removes elements. The second is the opposite. Fast adding and removing, but slow when accessing random items.

Now, let's assume you have a class that has methods that retrieve information about a car dealership. One method gets a list of all the available car manufacturers, while the other method gets all the cars the dealer has. In the first case, you would like to use ArrayList

because you do not expect the list of manufacturers to change much, whereas in the second case, you want LinkedList

to because you expect to sell and buy a lot of cars, thus making a lot of changes.



However, whoever uses these methods doesn't care if he is processing ArrayList

or LinkedList

. All it wants to do is use get(x)

and add(Car)

or remove(Car)

, which are all methods of the interface List

. Thus, your methods should have List

a return type, and they will determine what implementation they will provide, since that doesn't matter to whoever calls them.

It also gives you the advantage that you can change the second method in the future, such as provide LinkedList

in ArrayList

, if you decide you want quick checkout instead of quick add and delete. If the method was explicitly returning LinkedList

, you would need to go and change all the places it called to the new type. But if it just returns an interface, then no external changes are required!

+4


source







All Articles