java - actual difference between creating object using superclass reference -


this question has answer here:

what benefit create object using super class reference?

like

class people{ } class child extends people{ } public class demo{ public static void main(string []){ people p=new child();      //line 1 child d=new child();       //line 2 }  } 

i want know actual use of line 1 , line 2.

list l can refer object of implementation arraylist,linkedlist etc. first approach :

list l=new arraylist(); 

you can change implementation later without affecting code references it.

list l=new linkedlist(); 

this called coding interface , not implementation. in accordance liskov substitution principle. code interface when know or anticipate change and/or different implementation.

the reason can consider declaring

arraylist ar=new arraylist(); 

when sure implementation not change in future ( remember , change constant ) , want use arraylist specific methods in code not defined in list interface, , don't want use cast :

list list = new arraylist(); ((arraylist) list).trimtosize(); 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -