0

I've always wondered what are the benefits of this type of instantiation of a list in java that I see in a lot of code

List<Object> objList = new ArrayList<Object>();

as opposed to

ArrayList<Object> objList = new ArrayList<Object>();

Both are valid ways to instantiate a Java ArrayList object but why use the first one?

Why should objList be casted as the interface rather than the actual class that implements it? What are the cases where this is helpful?

Also, on compiler level, when we invoke a method on objList that is specific to ArrayList but not the interface List, roughly speaking, how does compiler "know" that method belongs to ArrayList when objList is casted only as a generic obj that is an instance of some class that implements List?

tlaminator
  • 946
  • 2
  • 9
  • 23
  • This question screams duplicate. – Hovercraft Full Of Eels Dec 10 '15 at 23:21
  • @HovercraftFullOfEels so does 70% of what I see on a daily basis on SO. But somebody's going to answer anyway. – Eugene K Dec 10 '15 at 23:22
  • `"how does compiler "know" that method belongs to ArrayList"` -- the compiler doesn't know, but the JVM knows through the magic of polymorphism and method binding. Look up "virtual method table". – Hovercraft Full Of Eels Dec 10 '15 at 23:23
  • @EugeneK: yes, most questions are duplicates, but this one is egregiously so. Hopefully the original poster (and all of us) will do searching first before asking such questions in the future. – Hovercraft Full Of Eels Dec 10 '15 at 23:25
  • [Link to a Google search on possible duplicates on this site](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=java+list+vs+arraylist+polymorphism+site:http:%2F%2Fstackoverflow.com%2F). – Hovercraft Full Of Eels Dec 10 '15 at 23:26
  • 1
    @HovercraftFullOfEels I think you're misreading the OP. "Also, on compiler level, when we invoke a method on objList that is specific to ArrayList but not the interface List," the compiler refuses to compile that program. It doesn't "know" that object belongs to `ArrayList`; you've deliberately told it to forget. – Louis Wasserman Dec 10 '15 at 23:27
  • @LouisWasserman: true, I did not see that. It's impossible to do that without first casting, which undoes the some of the benefits of coding to the interface. – Hovercraft Full Of Eels Dec 10 '15 at 23:28

0 Answers0