Why LinkedList implements List interface again in java [duplicate] - java

Why do many Collection classes in Java extend the Abstract class and also implement the interface (which is also implemented by the given abstract class)?
For example, class HashSet extends AbstractSet and also implements Set, but AbstractSet already implements Set.

It's a way to remember that this class really implements that interface.
It won't have any bad effect and it can help to understand the code without going through the complete hierarchy of the given class.

From the perspective of the type system the classes wouldn't be any different if they didn't implement the interface again, since the abstract base classes already implement them.
That much is true.
The reason they do implement it anyways is (probably) mostly documentation: a HashSet is-a Set. And that is made explicit by adding implements Set to the end, although it's not strictly necessary.
Note that the difference is actually observable using reflection, but I'd be hard-pressed to produce some code that would break if HashSet didn't implement Set directly.

This may not matter much in practice, but I wanted to clarify that explicitly implementing an interface is not exactly the same as implementing it by inheritance. The difference is present in compiled class files and visible via reflection. E.g.,
for (Class<?> c : ArrayList.class.getInterfaces())
System.out.println(c);
The output shows only the interfaces explicitly implemented by ArrayList, in the order they were written in the source, which [on my Java version] is:
interface java.util.List
interface java.util.RandomAccess
interface java.lang.Cloneable
interface java.io.Serializable
The output does not include interfaces implemented by superclasses, or interfaces that are superinterfaces of those which are included. In particular, Iterable and Collection are missing from the above, even though ArrayList implements them implicitly. To find them you have to recursively iterate the class hierarchy.
It would be unfortunate if some code out there uses reflection and depends on interfaces being explicitly implemented, but it is possible, so the maintainers of the collections library may be reluctant to change it now, even if they wanted to. (There is an observation termed Hyrum's Law: "With a sufficient number of users of an API, it does not matter what you promise in the contract; all observable behaviors of your system will be depended on by somebody".)
Fortunately this difference does not affect the type system. The expressions new ArrayList<>() instanceof Iterable and Iterable.class.isAssignableFrom(ArrayList.class) still evaluate to true.

Unlike Colin Hebert, I don't buy that people who were writing that cared about readability. (Everyone who thinks standard Java libraries were written by impeccable gods, should take look it their sources. First time I did this I was horrified by code formatting and numerous copy-pasted blocks.)
My bet is it was late, they were tired and didn't care either way.

From the "Effective Java" by Joshua Bloch:
You can combine the advantages of interfaces and abstract classes by adding an abstract skeletal implementation class to go with an interface.
The interface defines the type, perhaps providing some default methods, while the skeletal class implements the remaining non-primitive interface methods atop the primitive interface methods. Extending a skeletal implementation takes most of the work out of implementing an interface. This is the Template Method pattern.
By convention, skeletal implementation classes are called AbstractInterface where Interface is the name of the interface they implement. For example:
AbstractCollection
AbstractSet
AbstractList
AbstractMap

I also believe it is for clarity. The Java Collections framework has quite a hierarchy of interfaces that defines the different types of collection. It starts with the Collection interface then extended by three main subinterfaces Set, List and Queue. There is also SortedSet extending Set and BlockingQueue extending Queue.
Now, concrete classes implementing them is more understandable if they explicitly state which interface in the heirarchy it is implementing even though it may look redundant at times. As you mentioned, a class like HashSet implements Set but a class like TreeSet though it also extends AbstractSet implements SortedSet instead which is more specific than just Set. HashSet may look redundant but TreeSet is not because it requires to implement SortedSet. Still, both classes are concrete implementations and would be more understandable if both follow certain convention in their declaration.
There are even classes that implement more than one collection type like LinkedList which implements both List and Queue. However, there is one class at least that is a bit 'unconventional', the PriorityQueue. It extends AbstractQueue but doesn't explicitly implement Queue. Don't ask me why. :)
(reference is from Java 5 API)

Too late for answer?
I am taking a guess to validate my answer. Assume following code
HashMap extends AbstractMap (does not implement Map)
AbstractMap implements Map
Now Imagine some random guy came, Changed implements Map to some java.util.Map1 with exactly same set of methods as Map
In this situation there won't be any compilation error and jdk gets compiled (off course test will fail and catch this).
Now any client using HashMap as Map m= new HashMap() will start failing. This is much downstream.
Since both AbstractMap, Map etc comes from same product, hence this argument appears childish (which in all probability is. or may be not.), but think of a project where base class comes from a different jar/third party library etc. Then third party/different team can change their base implementation.
By implementing the "interface" in the Child class, as well, developer's try to make the class self sufficient, API breakage proof.

In my view,when a class implements an interface it has to implement all methods present in it(as by default they are public and abstract methods in an interface).
If we don't want to implement all methods of interface,it must be an abstract class.
So here if some methods are already implemented in some abstract class implementing particular interface and we have to extend functionality for other methods that have been unimplemented,we will need to implement original interface in our class again to get those remaining set of methods.It help in maintaining the contractual rules laid down by an interface.
It will result in rework if were to implement only interface and again overriding all methods with method definitions in our class.

I suppose there might be a different way to handle members of the set, the interface, even when supplying the default operation implementation does not serve as a one-size-fits-all. A circular Queue vs. LIFO Queue might both implement the same interface, but their specific operations will be implemented differently, right?

If you only had an abstract class you couldn't make a class of your own which inherits from another class too.

Related

Difference between these declaration of TreeSet

So I have to use a TreeSet in my code.
As TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable
and interface NavigableSet<E> extends SortedSet<E> which extends Set<E>
I can use any of these three declaration:
NavigableSet<String> myTreeSet= new TreeSet<>();
SortedSet<String> myTreeSet= new TreeSet<>();
Set<String> myTreeSet= new TreeSet<>();
I know I will be having access to only those method which are exposed by the Interface I am using in the declaration. Is there any other reason to consider for selecting a particular declaration for a TreeSet?
its basically what you allow others (or yourself) to use, as you are stated. Other methods you like to use with your TreeSet might depend on the actual declaration. So there might be a method requiring a SortedSet, but when you define your TreeSet as Set, it will not be able to proceed
Please, don't make preliminary decisions. If you don't need methods from NavigableSet don't use it. Just use Set<String>.
You should use which ever interface you like to program. But what makes the difference is to which interface you are programming. I mean, programming to an interface (declaration type) and not to the actual TreeSet collection.
Here is the best answer which explains Programming to an interface.
As a guiding rule always choose the most top level type possible because this allows greater decoupling from the client code towards the concrete implementation. Most of the time it is not important to the calling code to know which implementation is used, you just want to provide the behaviour not expose it. Said that, sometimes you will feel like needing a little more control, then you should go through the interfaces hierarchy until you find the necessary level of control, but this should be the exception, not the rule

AbstractList and List in java

I know that in Java most people declare a list using:
List l = new ArrayList();
But what would be the difference between that and
AbstractList l = new ArrayList();
What are the advantages of using an interface over an abstract class in this particular instance?
Original answer:
An abstract class allows you to define some shared functionality, while leaving other functionality to be defined by implementations. Thus, abstract classes are useful if you are going to create a family of similar classes that share some functionality but have customizations.
An interface doesn't allow you to define any functionality. It simply defines a set of method signatures that you know can be called on any object of a class that implements that interface.
I'd say the accepted practice is not to use an abstract class to fill the role of an interface. That is, an abstract class should be used for code sharing among related classes that you define, whereas an interface should be used for abstraction.
One reason not to use abstract classes to fill the role of interfaces is that a class cannot inherit from more than one class, but it can implement many interfaces. Thus, using abstract classes limits your design a lot more than using interfaces does.
Edit:
In this particular instance, the difference would be that if you later reassigned l to contain an object that implements List but does not derive from AbstractList, your code will throw an exception. Not all classes that implement List also extend AbstractList.
Using AbstractList limits you to only working with lists that are derived from the core AbstractList functionality. On the other hand, anyone could write a class that implements List using totally new code, and if you're using a variable of type List then you'll still be compatible with their new class that you've never seen before.
The fact that Java's lists are derived from AbstractList should be treated as an implementation detail that's internal to the Java library, not as an interface that you should code against.
The hierarchy is like...
ArrayList extends AbstractList implements List
and
AbstractList implements List
So,
whenever you are creating a object of ArrayList like given below, You will be creating object of ArrayList with reference of List
List list = new ArrayList();
Another thing to note is, why it is required to implement List in both class,
So,
it is for the purpose of showing that ArrayList implements List.
AbstractList in the whole picture is just for convenience and to
reduce code duplication between List implementations.
Reference: This SO Answer
In this case it wouldn't be really different. However it's a common code style to use the interface as the variable type, as the abstract implementation of AbstractWhatever class is mean to make it easier to create an implementation without having to implement all of the methods in the interface.
So it's a style issue, not really a technical one.

About the Java interface and polymorphism

I just met an strange case when reading the Java doc. Here is the link to Oracle's java doc on Arrays.asList method, http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)
There is an example in the doc
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
My question is, as List is an interface, why can we declare stooges as a 'List', rather than a concrete subclass implementing List(e.g. ArrayList or LinkedList)?
So does it mean that we can have a reference variable of interface type? It looks quit weird to me as I always think that interface stands only for polymorphism, and we should never really use a interface type variable.
Could anyone please give me some clue on this?
Think of the List interface as a guarantee. Any class that implements List will be guaranteed to have the methods of the interface. When Arrays.asList() returns a List you're not actually getting an interface, you're getting a concrete class that is guaranteed to implement the methods listed in the List interface.
As to your "we should never really use a interface type variable" you're actually suppose to do that. It's called "programming to the interface". It's much more flexible if you can return a List as opposed to something like a LinkedList. The caller of your method isn't coupled to your specific implementation internal implementation which might use, and return, a LinkedList. If at some point you wanted to return a ArrayList instead of the LinkedList the caller would not have to change any code because they only care about the interface.
What does it mean to "program to an interface"?
Just a word of note, Serializable is a marker interface and a little odd because of that. It doesn't guarantee that methods are there, but instead guarantees that the creator of the class that implements serializable has thought about the many issues associated with serializing a class (overriding readObject/writeObject, compatiblity with other serialized forms, and other issues http://www.javapractices.com/topic/TopicAction.do?Id=45). So Serializable is still offering a guarantee, like List is, but it isn't about method signatures, it's about an extralinguistic feature of the language.
http://en.wikipedia.org/wiki/Marker_interface_pattern
Using an Interface as a reference type is a perfectly valid practice in Java. For example, the Serializable interface will do this inside it's class, so that any object that is passed to it can be serialized.
This is also how Java provides something that resembles Multiple Inheritance. For example:
public interface A { }
public class B implements A {}
public class program {
B bClass = new B();
A aObject = (A)bClass;
}
That way the same object can be referenced with different reference types, and all without messing up an inheritance chain!
The interface defines a contract or a specification for an implementation. Which is the methods and their signature. So a class that implements an interface has to respect that contract. This way you can change implementation without affecting the code that uses interfaces for declaring variables.
In the example you mentioned:
You don't know what implementation of the List interface Arrays.asList is using unless you look into the code. So how would you know which one to use? (see javadoc for list interface to see what implementations it has)
The implementation is subject for change, what if Arrays.asList decides to use another implementation? Your code will be broken.
The signature of the method Arrays.asList is that it returns List<T> so if you want to have a concrete implementation as variable you'll have to cast that return value which is bad practice or to create new - let's say ArrayList - and copy all the elements into it, which is just an unnecessary overhead.
Effective Java by Bloch is a great book on Java best practices. In particular, item #52 talks about this: "If the appropriate interface types exist ... declared using the interface types."
The general notion is that, for greatest flexibility and understandability, you should use the type that best reflects the context, which is usually the interface. In the example, you provided, does the exact implementation matter or just that it is a List. Of course, if the code requires an ArrayList-specific method or if the code is relies on an ArrayList-specific behavior, then use the concrete class.
There are occasional exceptions, such as when using GWT-RPC, but this is for implementation reasons.
This is really good example of polymorphism power, if you like you can look at the source code of Arrays.asList() here Arrays.asList(T...a) ,you will find that it takes varibale length input and defines its own private static concrete class ArrayList that implements List interface rather than using the well known java.util.ArrayList or other java Collection type,
this may be to make it more efficient or something, you want to implement your own class and you return it to the user without overwhelming him by implementation details since there is an interface he can deal with your private class through.

Extending an object vs Implementing an interface

Trying to understand a question I got wrong on a test:
How does inheritance differ from implementing interfaces?
With inheritance, a class gains behavior from its superclass.
With interfaces, a class gains behavior from the interface it implements. (this is the one I chose)
With inheritance, a class must implement the methods defined by its superclass.
With interfaces, a class gains both instance variables and behaviors from the interface it implements.
The way I was thinking is that interfaces define behavior, while superclasses define characteristics... or are they the same? Or am I completely backwards in my understanding?
Edit: I guess I should specify that I do know the difference between interfaces and inheritance. I'm just wondering about the two options which use the term behavior. I don't know if the prof was nitpicking about terminology, or if he asked the question poorly.
I know that when you implement an interface, you have to implement all the methods as defined in the interface. As such, I would say that the interface defines the behavior that a class must have, but extending another superclass (although it does also define some behaviors (more can be given to the subclass), it doesn't seem to fit as strongly as the interface defining behaviors. If the class implements an interface, you can be sure that it has certain behaviors.
Maybe the question was meant to ask whether or not the interface itself has the code for the behavior, or if it's just the definition - which if worded that way, I would have known the answer.
I think some of your misunderstanding might stem purely from semantics. Perhaps a more straightforward way of describing an interface is that it defines an API but does not provide an implementation of that API. One caveat is that I will use Java for my example but in a language like C++, implementing an interface is inheritance of a special sort - namely inheriting from a class consisting of pure virtual functions.
In Java, for instance, you might have an EventListener interface defined as:
public interface IEventListener {
public void handleEvent(Event event);
}
The interface does not, to use the question's verbiage, say anything about how a class that implements the IEventListener interface will behave when it receives an event it only ensures that any class implementing this interface will have the characteristic of being able to receive an event of type Event.
Inheritance, on the other hand, allows super classes to also inherit behavior (implementation). For instance, consider the following Java base class:
public abstract BaseClass {
public void baseMethod(int value) {
System.out.println(int);
}
public class SubClass extends BaseClass {
}
Any class that inherits from BaseClass gains both the API (characteristics) of BaseClass and also the implementation (behavior). In other words not only can you invoke instanceOfSubClass.baseMethod(1), a characteristic, doing so will result in the behavior defined in the BaseClass, namely 1 being printed to the console.
So your answer (2) is incorrect because interfaces do not specify behavior (implementation) only API (characteristics). Inheritance can handle both.
I think the point of the question is to explain that inheritance is specifically useful when you want to share behavior and not just API. That said, implementation (behavior) can also be shared via composition and such a strategy is often better - see Item 16 in Bloch's Effective Java for an excellent discussion.
When you implement an Interface, you don't necessarily care much for the implementation. Also remember that you can implement as many interfaces as you want, since they only specify contracts but not how to fulfill them. The creator of the interface lets you take care of that.
When you extend an Object it's usually because you need some functionality which an already existing object already got the majority of, but will only need that bit extra. Or you want to redefine some of the existing behaviour of an already existing object.
To give you the answer: 1 is right. You don't HAVE to implement the methods of a superclass (Inheritance). Only when it's abstract the next subclass of this superclass needs to implement the methods (like in an interface).
An object implementing an x Interface tells the object that it must do all actions (methods) listed in the definition of an interface. So in the object that implements x, you need to implements all actions. An interface cannot be instanciated.
But when you inherit from an object y, the object y may already have an implementation of some actions. if not the method will be marked as abstract (in java) and you need to implement it in your inherited object.
This is a very common OO design question in Java.
Sincerely recommend this very good article on this topic that explains it well:
http://www.javaworld.com/javaqa/2001-04/03-qa-0420-abstract.html
The correct answer is 1. The answer you chose (option 2) is wrong because interfaces technically do not have any behavior. They are just a list of abstract methods. You can consider them more as a template on which you can base your classes. For example, suppose a project is split into two parts, which need to be integrated at the end. Each team could use a common interface to base their classes on, so that integration would be a much easier job.
with inheritance, you get a cat. with an interface, you get the skeleton of a cat.
You gain behavior and implementation from inheritance. Remember that a subclass inherits all non-constructor and private methods from it's superclass. This means that you may inherit functionality (implementation) of certain methods.
With implementation you gain just behavior. All you are doing with implementation is signing a contract with the compiler, saying that you promise to override all abstract methods defined in the implemented class or interface.
I hope this helped.

Why would both a parent and child class implement the same interface?

I inherited some legacy Java (1.4) code and this design decision appears regularly. I can't understand if there's any purpose or reason to it.
public interface SoapFacade extends iConfigurable{ }
public class SoapFacadeBase implements SoapFacade{
...
}
public class SoapFacadeImpl extends SoapFacadeBase implements SoapFacade{
...
}
As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface. In this scenario, everything from SoapFacade is implemented in SoapFacadeBase, but the method in iConfigurable is implemented in SoapFacadeImpl. However, that doesn't create a need to have SoapFacadeImpl implement SoapFacade.
Is there something I don't know about interfaces that would give this pattern some purpose or benefit? Are there underlying costs beyond lack of clarity that should drive refactoring it? Or should it simply be refactored for clarity/simplicity?
As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface.
No. Technically, it is completely redundant.
It does however document the fact that you intend SoapFacadeImpl to be a SoapFacade and it ensures that you get a compile error, if you (or someone else) decides to remove implements SoapFacade from the base class.
You see this pattern everywhere in the standard Java Collections API. ArrayList implements List even though its base class (AbstractList) already, does. Same holds for HashSet / AbstractSet and the Set interface.
If you use the interface also as a marker. Class.getInterfaces(); will only return directly instanced interfaces.
I actually find that design pointless. Implemented interfaces, as you stated, are just inherited, so there's no need to copy and paste "implements SomeInterface" on the children classes.
It's not clearer, smarter, or whatsoever...
It is nonsense, don't do it.
Especially in a public API like java collections. It's absolutely nonsense.

Categories

Resources