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 trialSoumitra Mehrotra
1,468 PointsIf list is an interface, then how come it has defined methods with full body?
We know that an interface has abstract methods by default, i.e we need to override those methods in a subclass. ArrayList is a subclass that implements List Interface. List<int> s=new ArrayList<int>(); so, we can see class ArrayList is upcasted to use the methods of List.But since list is an interface and has abstract methods, how come this line below works?
s.add(1);
2 Answers
Chris Jones
Java Web Development Techdegree Graduate 23,933 PointsHi Soumitra,
Good question!
You're correct that List is an interface. However, ArrayList does not inherit List, it implements List. Casting involves inheritance and because ArrayList does not inherit List, there is no upcasting. Inheritance is the term that is used when a subclass extends an abstract class. We see the the inheritance chain at the top left hand corner of the Java docs for ArrayList (https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html). The ArrayList class inherits from java.util.AbstractList<E>
.
What is happening when you write List<int> s=new ArrayList<int>()
is implementation of an interface. You're correct that List has "abstract" (it's not really abstract because it doesn't use the abstract
key word) method signatures. ArrayList implements the List interface and by doing so guarantees that it has written the body of these "abstract" methods (this is called implementing the interface).
So, to recap, classes can implement
interfaces and extend/inherit
abstract classes. Because List is an interface, ArrayList implements List and ArrayList writes the body of the "abstract" method signatures contained in List.
You're asking good questions! I hope my answer wasn't confusing, but let me know if it was or if you have more questions!
Keep at it!
Gal Krisztina
16,475 PointsThank you, it also hepled me ! :)
Chris Jones
Java Web Development Techdegree Graduate 23,933 PointsI'm glad to hear that, Gal! Keep pushing through! Inheritance and implementation can be a difficult topic!
Soumitra Mehrotra
1,468 PointsSoumitra Mehrotra
1,468 PointsThanks a lot, Chris. I got it .!!
Chris Jones
Java Web Development Techdegree Graduate 23,933 PointsChris Jones
Java Web Development Techdegree Graduate 23,933 PointsNot a problem! Glad to help!