Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.help > #1558

Re: Interchanging objects?

From Lew <lewbloch@gmail.com>
Newsgroups comp.lang.java.help
Subject Re: Interchanging objects?
Date 2012-02-09 09:21 -0800
Organization http://groups.google.com
Message-ID <6097014.139.1328808112771.JavaMail.geo-discussion-forums@pbcxd5> (permalink)
References <bb014e7e-2bf1-4d55-8677-6e2514826da5@p7g2000yqk.googlegroups.com> <2362859.192.1328425259754.JavaMail.geo-discussion-forums@prhb20> <9f687d98-30d7-4838-b09d-5ff6a77139b9@1g2000yqv.googlegroups.com> <0iq6j7t80gambj8ck9nbpldtscdes3d6pv@4ax.com>

Show all headers | View raw


Roedy Green wrote:
> Davej wrote, quoted or indirectly quoted someone who said :
> >I have been trying to think of a convenient way to interchange objects
> >that provide calculations that are done slightly differently. The
> >objects all have the same method names and return the same types. Is
> >there an elegant way to accomplish this? Thanks.
> 
> This is what an interface is for.  All the classes that perform the
> same operations but in a different way all implement the same
> interface.  Then you can refer to any objects of any of those classes
> by their interfacename.  What you call myinterface.calcBiggest for
> example, each object will uses its class's version of calcBiggest.
> 
> See http://mindprod.com/jgloss/interface.html

After you understand how interfaces work to encapsulate common types of 
behavior (as opposed to common implementations of behavior), you can use Java 7 
"closures" effectively. The Java version of closures is syntactic sugar for 
single-abstract-method (SAM) interfaces, that is, interfaces that define 
exactly one abstract method.

Example:

 public interface Closure
 {
   int performOp(int x, int y);
 }

The operations performed by 'performOp()' can be anything that operates on two 
'int' values and returns an 'int'.

-- 
Lew

Back to comp.lang.java.help | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

Interchanging objects? Davej <galt_57@hotmail.com> - 2012-02-04 12:02 -0800
  Re: Interchanging objects? Lew <lewbloch@gmail.com> - 2012-02-04 23:00 -0800
    Re: Interchanging objects? Davej <galt_57@hotmail.com> - 2012-02-05 07:41 -0800
      Re: Interchanging objects? Lew <lewbloch@gmail.com> - 2012-02-05 11:34 -0800
      Re: Interchanging objects? Roedy Green <see_website@mindprod.com.invalid> - 2012-02-08 22:42 -0800
        Re: Interchanging objects? Lew <lewbloch@gmail.com> - 2012-02-09 09:21 -0800
  Re: Interchanging objects? Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-02-07 08:09 -0500

csiph-web