Reputation: 2015
Hello StackOverflowers.
This is almost certainly a very basic question regarding object instantiation but in the following code sample:
List myList = new LinkedList();
Is this a form of inheritance? In other words, would one read this has LinkedList "is a" List and therefore inherits the methods defined in the List class? If so, provided a user constructed two classes of his or her own and used the same syntax as above, would the answer be the same?
Thanks all.
Caitlin
Upvotes: 4
Views: 104
Reputation: 103135
There is a principle that says "Always program to the interface not the implementation". LinkedList is an implementation of the List interface. That is, List simply specifies what a List can do but does not say how it does it.
The LinkedList class "obeys" the specification of a List and as such when we write programs we can depend on the LinkedList behaving exactly the way the List specified. This makes for more robust programs because if you decided to use another type of List, say an ArrayList, then your program code does not change because you did not depend on the implementation details of the List.
When you declare a variable as in
List myList;
The List type is referred to as the "apparent" type. That is, the compiler will treat myList as a List in the rest of your code. You cannot refer to any feature of myList that is not part of the List specification (without casting and breaking the principle).
When you instantiate the object as in
= new LinkedList();
the LinkedList type is known as the "actual type". The compiler does not care about this so much. It only matters at run time.
Upvotes: 1
Reputation: 51711
Is this a form of inheritance?
No.
would one read this has LinkedList "is a" List
Yes.
and therefore inherits the methods defined in the List class?
No. List
is an interface and therefore cannot be extended/inherited (only implemented). But LinkedList
still passes as IS-A
because it implements all the methods required by the List
interface.
If a user constructed two classes of his or her own with one being the base class and the other derived from it then yes it would be inheritance. But, the following
BaseType base = new SubType();
doesn't exactly demonstrate inheritance but polymorphism made possible by inheritance i.e. since the sub type IS-A
base type as well it can be assigned to a base type reference.
Upvotes: 5
Reputation: 7213
Not quite, because List
is an interface which LinkedList
implements, not a superclass of LinkedList
. You should read up on interfaces. There is no inheritance of List
's methods - instead, there is simply a requirement that LinkedList
has the methods listed in the List
interface.
Upvotes: 4