Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!border3.nntp.dca.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail From: Lew Newsgroups: comp.lang.java.help Subject: Re: Interchanging objects? Date: Thu, 9 Feb 2012 09:21:52 -0800 (PST) Organization: http://groups.google.com Lines: 33 Message-ID: <6097014.139.1328808112771.JavaMail.geo-discussion-forums@pbcxd5> References: <2362859.192.1328425259754.JavaMail.geo-discussion-forums@prhb20> <9f687d98-30d7-4838-b09d-5ff6a77139b9@1g2000yqv.googlegroups.com> <0iq6j7t80gambj8ck9nbpldtscdes3d6pv@4ax.com> NNTP-Posting-Host: 173.164.137.214 Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 X-Trace: posting.google.com 1328808113 19944 127.0.0.1 (9 Feb 2012 17:21:53 GMT) X-Complaints-To: groups-abuse@google.com NNTP-Posting-Date: Thu, 9 Feb 2012 17:21:53 +0000 (UTC) In-Reply-To: <0iq6j7t80gambj8ck9nbpldtscdes3d6pv@4ax.com> Complaints-To: groups-abuse@google.com Injection-Info: glegroupsg2000goo.googlegroups.com; posting-host=173.164.137.214; posting-account=CP-lKQoAAAAGtB5diOuGlDQk0jIwmH0T User-Agent: G2/1.0 X-Google-Web-Client: true Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.help:1558 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