My doubt is between a simple class with implementations of methods and an interface. not the abstract class. Why cant we just make a List Class , give all the method implementations and make Array List or Linked list to extend it. arent the implementations of methods same.
Asked
Active
Viewed 796 times
1
-
4Other list implementations could then never `extend` anything else – QBrute Apr 05 '17 at 14:51
-
@QBrute: I know it seems obvious, but that's an answer, not a comment. – T.J. Crowder Apr 05 '17 at 14:53
-
"not the abstract class" then you would need to provide implementation for all methods. Which implementation would you use? Maybe one like ArrayList which is backed up by array. But in that case how would you create other lists like LinkedList? You would need to extend that `List` (really ArrayList) but then you would also inherit all those redundant things like field for array holding data. List being interface is more intuitive. – Pshemo Apr 05 '17 at 14:56
-
1You should know that the standard implementations of `List` actually inherit from `AbstractList`, which has default implementations for some of the methods. You may find it interesting to read the code for `ArrayList` vs. `LinkedList` and see which methods are not implemented in `AbstractList`. – RealSkeptic Apr 05 '17 at 14:58
-
1"arent the implementations of methods same" But that's the point of it, to have different implementations with different runtime characteristics, e.g. memory usage and performance, but identical behavior. – weston Apr 05 '17 at 14:59
2 Answers
8
No, the implementations are not the same. A linked list contains a collection of doubly linked nodes and is optimized for fast insertion/removal. An array list is backed by an array of references and is optimized for random access, but will be less efficient as elements are added and removed.
Defining List
as an interface allows callers to apply list-based semantics regardless of the internal details.

Greg Brown
- 3,168
- 1
- 27
- 37
1
In Java, multi-inheritance is not possible. So if a class extends
another class, it cannot extend anything else. Whereas implementing an interface
is unrestrained. You can implement
multiple interfaces with one class.

QBrute
- 4,405
- 6
- 34
- 40