From what I've read, the first LinkedList/List determines what methods
can be used.
Yes, the "first LinkedList/List" is the type of the reference you are declaring. You can invoke the methods exposed by a reference's type on that reference, including inherited ones, and no others.
So for test1, you can do test1.peek() while you can't for
test2.
Yes.
Is that because, for test2, that you are creating a LinkedList
but going to be implementing the methods of the List interface?
No. You are not implementing anything there. You are initializing references test1
and test2
to refer to objects of class LinkedList
, which is a concrete class that implements
List
, and therefore provides concrete implementations of all methods defined by the List
interface. LinkedList
also provides implementations of some methods defined by other interfaces and by superclasses, and, in principle, it could define and implement some methods unique to it.
In
other words, for test2, you've created a LinkedList with a prev & next
node but are choosing to implement the methods outlined in the List
interface?
Again, you are not implementing any methods here. By choosing to access a LinkedList<Integer>
object via a reference of type List<Integer>
, you ensure that only those LinkedList
methods that are defined by List
can be invoked via that reference. That doesn't change the nature of the object itself. There will be other references to it at least sometimes, some of them of type LinkedList<Integer>
. Those can be used to invoke methods exposed by LinkedList
but not by List
on the object.
Guess I'm a bit confused because I thought LinkedList is a class that
implements the List interface,
Yes.
but for test2, we're creating a
LinkedList and implementing a List again?
Every LinkedList
is a List
. This is one of the main consequences of the fact that former class implements
the latter interface. By accessing an object of class LinkedList
via a reference of type List
, you limit yourself to using only those parts of it that are defined by List
, but you have not changed the object itself in any way. It is still a LinkedList
.
Consider human roles. I'm a son, a brother, a father, an employee, a friend, and many other things, but most people in my life interact with me according to only one or two of those roles. For example, my boss regularly asks me, her employee, to do various pieces of work for her, but she would never ask me to give her a weekly allowance as if I were her father.
Types, and in particular interface types, can be regarded like those roles. If you need an employee, it doesn't have to be someone exactly like me -- it can be anyone who can fill the "employee" role. And operating in that role does not make anyone not have all their other roles.