java - method resolution when instantiating an interface -


edit: forgot code snippet _ added here

i trying learn java book 'learning java' has following code snippet listed example interface callbacks. in code snippet, there 1 class implementing interface textreceiver. question - since code instantiating interface directly, if there class implemented interface textreceiver , provided whole different method body interface method receivetext 1 in tickertape, how java resolve reference method receivetext in sendtext method of textsource? seems introduce ambiguity - also, seems credence have seen online not being able instantiate interfaces - wanted confirm before assuming

interface textreceiver {     void receivetext( string text ); }  class tickertape implements textreceiver {     public void receivetext( string text ) {         system.out.println("ticker:\n" + text + "\n");     } }  class textsource {     textreceiver receiver;      textsource( textreceiver r ) {         receiver = r;     }      public void sendtext( string s ) {         receiver.receivetext( s );     } } 

i tried writing myself figure out, got stuck issues compiling since of these classes in same class. know sounds n00bish - figured guys might have quick guidance offer.

thanks in advance!!!

java interfaces cannot instantiated, programmer has specify implementation of interface wants instantiate.

for example, if try (replace interface name of interface):

interface = new interface(); 

you error, because interface cannot instantiated.

what must (replace implementation name of implementation of interface):

interface = new implementation(); 

as can see, tell program implementation use interface. there's no room ambiguity.

in example, class textsource not instantating interface textreceiver (instantiation occurs "new" keyword). instead, has constructor receives implementation of interface parameter. therefore, when call textsource must tell implementation of textreceiver use.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -