I have heard several times that when instantiating objects you should do:
"Interface" name = new "Class"();
For example for the class linkedlist that implements List
:
List<String> name = new LinkedList<String>();
LinkedList
implements many interfaces, including queue, deque, etc. What is the difference between the above code and
LinkedList<String> name = new LinkedList<String>();
or
Queue<String> name = new LinkedList<String>();
Why must the type be specified twice as well; it seems redundant but oracledocs don't seem to mention it.
Interface is basically a complete abstract class. That means Interface only have deceleration of method not their implementation. So if we don't have any implementation of a method then that means if we create object of that interface and call that method it compile nothing as there is no code to compile.
Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.
You want the coupling of your code to be as loose as humanly possible. If you never couple to anything but interfaces, then that is as loosely coupled as you can get. Ultimately, this is the bottom-line reason why you should use interfaces: They provide a very thin — but very powerful — abstraction to your code.
Yes, you can define a class inside an interface. In general, if the methods of the interface use this class and if we are not using it anywhere else we will declare a class within an interface.
LinkedList<String> name = new LinkedList<String>();
is redundant in Java 7. It can be rewritten to LinkedList<String> name = new LinkedList<>();
.
The reason you want to write something similar to:
// Java 7 way:
List<String> name = new LinkedList<>();
is to provide you with the freedom of changing your data collection later, if you change your mind. Your code is much more flexible this way. What you should note about this, is that the methods you are able to use are limited to the left-hand side type (List
in this case). This means that you may not get all the functionality you want, if you use a type that is higher in the hierarchy (Object
being the extreme example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With