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 trialJasmeet Singh
20,145 PointsI don't know if it sounds stupid but can someone please help me figure out this confusion.
In the videos, Craig said that in order to use an interface we need to "implement" it like he did with the Comparable interface. then again he said that Serializable is also an interface but this time he "imported" as well as "implemented" the interface again he said that List is also an interface but this time he "imported" the List interface it rather than implementing it. It's pretty confusing.
2 Answers
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 PointsHi Krishana,
interfaces, just like classes, need to be imported if they don't belong to the core java.lang package which gets imported automatically.
Craig made the Comparable and Serializable interfaces be implemented by classes. With list he didn't implement the interface, he just used it to declare variables of the List type.
Implementing an interface:
class TestClass implements TestInterface {
...
}
Declaring a variable that implements an interface:
List<String> testList = new ArrayList<>();
ArrayList implements the List interface, that's why you can declare it as being of the type List. This has several benefits, for example, you could later assign a TreeList instead of an Arraylist and your code would still work.
Hope that helps.
Kind Regards, Florian
Adriano Martinelli Ianase
9,621 PointsHey Jasmeet, how are you doing?
Just adding to Florian answer, in his example:
class TestClass implements TestInterface {
...
}
You could also do in your main function:
TestInterface ti = new TestClass();
Because TestClass implemented TestInterface. This can lead to some restrictions on the ti object later, but I think the course will run into it later.
Best, Adrian