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 trial

Java Java Data Structures Exploring the Java Collection Framework Using ArrayLists

Soumitra Mehrotra
Soumitra Mehrotra
1,468 Points

If 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Jones
Java Web Development Techdegree Graduate 23,933 Points

Hi 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!

Thank you, it also hepled me ! :)