Search code examples
javainterfaceimplementation

Why should I use an interface when there is only one implementation class?


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?


Solution

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