Why do we first declare subtypes as their supertype before we instantiate them?

前端 未结 12 945
轻奢々
轻奢々 2021-02-01 19:27

Reading other people\'s code, I\'ve seen a lot of:

List ints = new ArrayList();
Map map = new HashMap();
12条回答
  •  孤独总比滥情好
    2021-02-01 20:00

    Is a design principle that you program to the interface and not to the implementation.

    That way you may provide later a new implementation to the same interface.

    From the above link Eric Gamma explains:

    This principle is really about dependency relationships which have to be carefully managed in a large app. It's easy to add a dependency on a class. It's almost too easy; just add an import statement and modern Java development tools like Eclipse even write this statement for you. Interestingly the inverse isn't that easy and getting rid of an unwanted dependency can be real refactoring work or even worse, block you from reusing the code in another context. For this reason you have to develop with open eyes when it comes to introducing dependencies. This principle tells us that depending on an interface is often beneficial.

    Here, the termin interface refers not only to the Java artifact, but the public interface a given object has, which is basically composed of the methods it has, so, it could be a Java interface ( like List in your example ) or a concrete superclass.

    So in your example if you ever want to use a LinkedList instead it would be harder because the type is already declared as ArrayList when just list would've been enough.

    Of course, if you need specific methods from a given implementation, you have to declare it of that type.

    I hope this helps.

提交回复
热议问题