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

前端 未结 12 950
轻奢々
轻奢々 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 19:55

    Quick answer? Using interfaces and superclasses increases the portability and maintainability of your code, principally by hiding implementation detail. Take the following hypothetical example:

    class Account {
        private Collection transactions;
    
        public Account() {
            super();
            transactions = new ArrayList(4);
        }
    
        public Collection getTransactions() {
            return transactions;
        }
    }
    

    I've declared a contract for an Account that states that the transactions posted to the account can be retrieved as a Collection. The callers of my code don't have to care what kind of collection my method actually returns, and shouldn't. And that frees me to change up the internal implementation if I need to, without impacting (aka breaking) unknown number of clients. So to wit, if I discover that I need to impose some kind of uniqueness on my transactions, I can change the implementation shown above from an ArrayList to a HashSet, with no negative impact on anyone using my class.

    public Account() {
        super();
        transactions = new HashSet(4);
    }
    

    As far as your second question, I can say that you use the principal of portability and encapsulation wherever they make sense. There are not a terrible lot of CharSequence implementations out there, and String is by far the most used common. So you just won't see alot of developers declaring CharSequence variables in their code.

提交回复
热议问题