java - Using a interface type to instantiate a class object that implements the interface -


some confusion using interface type instantiate class object. why need interface type? when can use class instead? class implements interface anyway. know cannot instantiate interface.

many suggestions,

   public interface sortrecords {         int query(int rowid);     }      public class ourprice implements sortrecords {         @override         public int query(int rowid) {             return 0;         }     }      public void test() {         /*           * why has interface type?           */         sortrecords sorterv1 = new ourprice();         sorterv1.query(1);          /*           * why not this?           */         ourprice sorterv2 = new ourprice();         sorterv2.query(2);     } 

the interface declares contract, , provides freedom specify other class providing same contract. code referencing interface agnostic implementation you're providing.

in above example, it's not particularly useful. however, in wider context, factory provide implementation likes (even varying during runtime). consumer, don't have worry. communicate using interface , contract (methods) provides.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -