I'm new at programming and I'm learning Java. I was just wondering why I should use an interface when there is only one implementation class?
An interface defines common functionality across unrelated classes. For example, all sorts of classes that look nothing like each other may have the need to safely get rid of the resources they use.
Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes.
In most cases, a final class is the best thing you can create. If a user doesn't like your class, they can simply choose not to use it. However, if you're building up a hierarchy of objects you should introduce an interface for every class.
Why do you want to program to abstractions and not implementations? The simple answer is this: An interface is the smallest, thinnest, and least complicated thing you can couple your code to. And I hope you know by now that loosely coupled code is good.
You do this to prevent others from accessing your implementing type. For example, you could hide your implementing type inside a library, give the type package access, and return an instance of your interface to the users of your library:
// This is what the users of your library know about the class // that does the work: public interface SomeInterface { void doSomethingUseful(); void doSomethingElse(); } // This is the class itself, which is hidden from your clients class MyImplementation implements SomeInterface { private SomeDependency dependency = new SomeDependency(); public void doSomethingUseful() { ... } public void doSomethingElse() { ... } }
Your clients obtain objects like this:
public class MyFactory { static SomeInterface make() { // MyFactory can see MyImplementation return new MyImplementation(); } }
This trick becomes useful when the implementation uses lots of libraries. You efficiently decouple the interface of your library from its implementation, so that the user wouldn't have to know about the dependencies internal to your library.
One reason is to maintain the open/closed principle, which states that your code should be open for extension, but closed for modification. Although you only have one implementing class now, chance is that you will need another differing implementation class with the passing of time. If you extract the implementation into an interface beforehand, you just have to write another implementing class ie. You don't have to modify a perfectly working piece of code, eliminating the risks of introducing bugs.
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