K
K
KR2_theBest2016-03-21 05:09:35
Java
KR2_theBest, 2016-03-21 05:09:35

Why write like this?

Hello everyone. I'm just learning. I know roughly what polymorphism is, but sometimes I come across such lines like List values ​​= new ArrayList(); why not just write ArrayList array = new ArrayList();? Let's assume (I don't know for sure), but if we assume that ArrayList is a child of List, then it turns out that the first option is truncated.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nirvimel, 2016-03-21
@KR2_theBest

This is done in order to reserve the opportunity to subsequently change the implementation without changing the interface. For example, in the future it may be necessary to replace the implementation of ArrayList with LinkedList if the type of the variable was specified as a concrete class, by which time the code might already have made various calls to class-specific methods that go beyond the boundaries of the List interface. In this case, when replacing the implementation with LinkedList, one would have to look in the code and root out all references to the specifics of ArrayList from there. How hellishly difficult this task is known to everyone who had to work on large projects. Therefore, people familiar with this problem prefer to prevent such problems in advance, that is, in all places where a change in implementation is possible in the future (that is, almost everywhere), try to use only interfaces, instead of relying on specific implementations. In this example, if the List interface was used as the variable type, then changing the implementation of ArrayList to LinkedList would be solved by replacing just one line, regardless of the scale of the project.

D
Danil Antoshkin, 2016-03-21
@TwerTrue

Maybe you should first understand what is List and what is ArrayList?
ArrayList - implements the List interface

R
Riard Brugekaaim, 2016-03-21
@OLDRihard

We sit down and study mat. part. In particular, for what there are interfaces, superclasses, and so on.
All collection types in Java have their own interface, which implements a standard set of methods for interacting with it. And standard classes differ in the way they organize content within themselves.
In most cases, frameworks do not restrict people to any particular type, but simply require the List universal interface for input, making it possible to choose the method that is more convenient for the user (or just create your own implementation of the interface)
And you need to put a belt on the NET tag! They were not invented to sculpt anything. There is already confusion in one of the answers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question