java - actual difference between creating object using superclass reference -
this question has answer here:
- why need interfaces in java? [closed] 5 answers
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
Post a Comment