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


i'm new @ programming , i'm learning java. wondering why should use interface when there 1 implementation class?

you prevent others accessing implementing type. example, hide implementing type inside library, give type package access, , return instance of interface users of library:

// users of library know class // work: public interface someinterface {     void dosomethinguseful();     void dosomethingelse(); }  // class itself, hidden clients class myimplementation implements someinterface {     private somedependency dependency = new somedependency();     public void dosomethinguseful() {         ...     }     public void dosomethingelse() {         ...     } } 

your clients obtain objects this:

public class myfactory {     static someinterface make() {         // myfactory can see myimplementation         return new myimplementation();     } } 

this trick becomes useful when implementation uses lots of libraries. efficiently decouple interface of library implementation, user wouldn't have know dependencies internal library.


Comments

Popular posts from this blog

Redirect to a HTTPS version using .htaccess -

Unlimited choices in BASH case statement -

javascript - jQuery: Add class depending on URL in the best way -