Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you assign an objects to an interface?

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.

like image 438
Dax Duisado Avatar asked Oct 26 '13 21:10

Dax Duisado


People also ask

Why do we create object of interface?

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.

Can you assign an object to an interface?

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.

Why should you program to an interface?

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.

Can we assign class to interface?

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.


1 Answers

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).

like image 87
Birb Avatar answered Oct 13 '22 01:10

Birb