多态召唤 [英] Polymorphic call

查看:117
本文介绍了多态召唤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java的新手,我已经在许多地方的代码中看到了我的老年人宣称为



列出myList = new ArrayList (); (option1)



而不是



ArrayList myList = new ArrayList(); (option2)



你能告诉我为什么人们使用Option1,有什么优势吗? / p>

如果我们使用option2,我们是否会错过任何优势或功能?

解决方案

使用option1的优点,即 List myList = new ArrayList(); 是关于方法的多态行为。比如说,你可以有一个方法,它接受List类型的参数,

  someMethod(List lst)
{
lst.doSomething();
//做其他事情.....
}

在此方法 lst 可以是类型的链接列表 ArrayList CopyOnWriteArrayList


I am new to java, I have seen in the code at many places where my seniors have declared as

List myList = new ArrayList(); (option1)

Instead of

ArrayList myList = new ArrayList(); (option2)

Can you please tell me why people use Option1, is there any advantages?

If we use option2, do we miss out any advantages or features?

解决方案

The advantage of using option1, ie, List myList = new ArrayList(); is to have polymorphic behaviour with respect to methods. Say, for example, you can have a method which takes arguments of type List,

someMethod(List lst)
{
   lst.doSomething();
   //do somethng else.....
}

In this method lst can be of type Linked List, ArrayList or CopyOnWriteArrayList.

这篇关于多态召唤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆