Rohit Guptaaaaa wrote:Hey i am not getting the concept of interfaces.I know they are used to implement multiple inheritances.
True, but that's not the main reason they exist.
I don't know the meaning of a class calls a method using an interface?
Me neither. A class
implements an interface, and that means that it must provide actual code for
all methods defined
in the interface.
It doesn't "call a method using an interface", except in the sense that you can
declare a variable as an interface type, and then call one of the
interface's methods on that variable. But that's no different to declaring a variable as a supertype of the class that's actually used to initialize it, viz:
private Bmw bmw = new BmwX3();
An interface is simply a supertype of
all classes that implement it.
I also know the example that we create an interface car with certain methods so that a class like bmw which implements the car interface has to implement these methods. But I don't know how interfaces come handy?
Because interfaces are proper types, so you can use them any place you might otherwise use a
class to declare a type.
Take the following declaration:
private ArrayList<String> list = new ArrayList<String>();
In this case, our code is now tied to an
implementation (ie, a
class - ArrayList), so if we use that type in a hundred different places in our program, and later on discover that
ArrayList was the
wrong choice - for example, we work out that it would have been much faster if we'd defined '
list' as a
LinkedList - we now have to change our program in 100 different places.
But if we change that definition to:
private List<String> list = new ArrayList<String>();
and use the
interface type in the other 100 places, we can change our entire program to use a
LinkedList with ONE change, viz:
private List<String> list = new LinkedList<String>();
Hope that helps to explain why interfaces are so useful. You might also want to read up a bit on
"programming to the interface".
Winston