Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEric Chan
4,254 PointsList myList = new ArrayList<String>(); Can anyone explain this in plain English?
I am having trouble grasping what this line of code does:
List myList = new ArrayList<String>()
Is it creating an instance of List (interface) and implementing it on an ArrayList (class) which should return String? With that being said, I am still having trouble digesting all the terms and concepts.
What exactly are Interface and Class and how these two objects interact?
Thanks a lot!
2 Answers
Mohit Kishore
13,935 Points"A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method. You can use interfaces in Java as a way to achieve polymorphism. "
Essentially it means that there is no logic how these methods in the interface should work. But if you have a class that extends an interface, then all the methods in the interface should be implemented and if you need more methods you can add them.
So in the above code that you have asked, List is an interface.
<String>
means the kind of data type is stored in each list item.
For the reason why we have
List myList = new ArrayList<String>();
checkout this question on stackoverflow
Please let me know if I was of any help.
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsHi Eric,
Just to add on what Mohit said List is an Interface, and it cannot be instantiated directly ( you can't define it as List<String> myList = new List() because Java compiler won't know which List Implementation you're referring to. ArrayList and LinkedList classes are the standard implementation of the List Interface.
The advantage of defining List as ArrayList or as LinkedList is that it makes it easier to swap your implementation later on to some other kind of List (e.g. a LinkedList, Vector) - you would only need to change that one line where you create it.
Hope that makes some sense.
Eric Chan
4,254 PointsEric Chan
4,254 PointsThanks Mohit
So can I say that Interface is the more like a framework while class is a more concrete construct? Whenever I encounter this kind of abstract concept, I just have to believe that it will come natural one day.
Mohit Kishore
13,935 PointsMohit Kishore
13,935 PointsHey Eric That's exactly what it is : )