Reason for - List list = new ArrayList();

reference link :http://stackoverflow.com/questions/18329311/reason-for-list-list-new-arraylist



QUESTION:

I've seen code like this many times:

List<String> list = new ArrayList<String>();

Why do people take the parent of ArrayList (and other classes) instead of the type of the generated object?



ANSWER1:

To decouple your code from a specific implementation of the interface.

This also helps you to move to another implementation of the List interface in the future.

For example -

You have List<String> names = new ArrayList<String>(); later on you decide that you should have used some other implementation of the List interface, say LinkedList so you would just change it to List<String> names = new LinkedList<String>(); and nothing breaks.


ANSWER2:

When someone writes code like this, he/she is trying to follow a basic OO design principle which says -

Program to an interface, not to a concrete implementation

I have explained this principle in one of my blog posts. Look in the Class Inheritance VS Interface Inheritance section.

To summarize the post, when you use a reference of a parent type to refer to an instance of a sub-type, you get a lot of flexibility. For example, if you ever need to change your sub-type implementation in the future, you will be able to do that easily, without changing much of your code.

Consider the following method -

public void DoSomeStuff(Super s) {
    s.someMethod();
}

and a call to this method -

DoSomeStuff(new Sub());

now, if you ever need to change the logic inside someMethod, you can easily do it by declaring a new subtype of Super, say NewSubType, and changing the logic inside that implementation. In this way, you will never have to touch other existing code which utilizes that method. You will still be able to use your DoSomeStuff method in the following way -

DoSomeStuff(new NewSubType());

Had you declared the parameter of DoSomeStuff to be of Sub, you would then have to change its implementation too -

DoSomeStuff(NewSubType s) {
    s.someMethod();
}

and it may also chain/bubble to several other places.

In terms of your collection example, this lets you change the list implementation that a variable is pointing to without much hassle. You can easily use a LinkedList in place of an ArrayList.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值