Java Variable type and instantiation -


this has been bugging me while , have yet find acceptable answer. assuming class either subclass or implements interface why use parent class or interface type i.e.

list list = new arraylist(); vehicle car = new car(); 

in terms of arraylist gives me access list methods. if have method takes list parameter can pass either list or arraylist arraylist list. within method can use list methods can't see reason declare it's type list. far can see restricts me methods i'm allow use elsewhere in code.

a scenario list list = new arraylist() better arraylist list = new arraylist() appreciated.

using interface or parent type recommended if need functionality of parent type. idea explicitly document don't care implementation, making easier swap out concrete class different 1 later.

a example java collection classes:

if use list, set etc. instead of e.g. arraylist, can later switch arraylist linkedlist if find gives e.g. better performance. that, change constructors (you don't have change them all, can mix). rest of code still sees instance of list , continues working.

if used arraylist explicitly, you'd have change everywhere it's used. if don't need arraylist specifically, there's nothing gained using on interface.

that's why it's recommended (e.g. in "effective java" (j.bloch), item 52: "refer objects interfaces".) use interfaces if possible.

also see related question: why classes tend defined interface nowadays?


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -