What is the advantage of using Interfaces in Java?
I know people will say it adds a layer to the system that hiues the functionality of Class1 from Class2, but I mean pratically, from a developers point of view what's the advantage? Because looking at the sample below, you have to call the class (CLass1) to create a new instance via the Interface anyway.
What advantage does using the Interface give you?
Also when is/isn't a good time to use interfaces? Is there a sort of rule to it? I mean is it worth using an interface for a Bean that just has a number of get/set methods (user details say) in it?
First, I think the title of your post should be "Interfaces, why do we need them?"
Second, you should declare that Class1 implements MyInt, otherwise you will not be able to assign an instance of it to a the "abc" reference, which is of type MyInt.
I think interfaces are mainly intended to allow the programmer to limit dependencies between different parts of his code. For instance if I write a sort method I can write it to take an instance of my special list class as an argument:
But I could also declare an interface List which exposes all the methods that I need to carry out the sorting and write a method that takes an object of that type:
Now my sort method is not dependent on MySpecialListClass. I only need to make sure that MySpecialListClass implements List.
I have changed the dependencies from
This means, for instance that I can change and recompile MySpecialListClass without recompiling the module that contains sort.
Read Jan van Mansum 's reply one more time. Slowly.
Yes, you want to introduce the 'in-directness' (as you call it) into the code to de-couple the classes. So, in the future you can update/change the implementation of the method with [almost] no effect to the rest of the code.
This has more advantages in distributed applications. You will find out if you don't already know.
"It is almost always answered in the API" - Murali Nanchala